Documentation
¶
Overview ¶
Package client implements haistack-client, the generic-first Go SDK for FHIR REST and HAIStack sync endpoints.
haistack-client is the outbound HTTP counterpart to pkg/http. It owns request construction, auth injection, retry/backoff, response decoding, OperationOutcome parsing, and focused sub-clients for SMART, bulk export, subscriptions, and sync. Resource lifecycle, persistence, indexing, and server behavior remain in lower layers.
Design principles ¶
Envelope-first API:
- CRUD and search return types.ResourceEnvelope with normalized FHIR JSON.
- Typed helpers for Patient, Observation, and Encounter are thin wrappers over the generic API — not a separate transport stack.
- Callers can use envelope APIs, raw JSON-in/JSON-out helpers, or ResourceEnvelope.DecodeInto and typed field getters; generated FHIR structs are optional.
Transport-only sync boundary:
- SyncClient defines HTTP wire shapes for POST /sync/push and GET /sync/pull.
- pkg/sync remains transport-agnostic; SDK DTOs mirror LocalEvent, PushResult, and CanonicalEvent so pkg/sync.Engine callers can bridge without custom mapping.
- Node ID and tenant ID are explicit on every sync request; they are not inferred from global client state alone.
FHIR-first responses:
- application/fhir+json for FHIR payloads.
- Non-2xx responses decode into types.OperationOutcome when the body is FHIR JSON.
- 429 and 5xx are retryable by default; 4xx are not unless RetryPolicy overrides.
- SearchResult preserves raw bundle JSON for advanced callers.
Shared request pipeline:
- All outbound calls flow through a single do() path: build request, inject TokenProvider headers, apply DefaultHeaders, execute with retry/backoff, decode success or map failure to client.Error.
Package boundaries ¶
- pkg/client — outbound HTTP transport, SDK surface, sync wire contract
- pkg/http — inbound FHIR REST adapter (server-side inverse of this SDK)
- pkg/types — ResourceEnvelope, ResourceCodec, OperationOutcome
- pkg/sync — transport-agnostic sync models and Engine orchestration
- pkg/smart — server-side token/assertion validation and auth adaptation
SMART token exchange lives in pkg/client (outbound OAuth). Token validation for inbound requests stays in pkg/smart; wire a TokenProvider from exchanged tokens.
Public API ¶
Core client:
- New(Config) (*Client, error) — construct the SDK client
- Client.Create / Read / Update / Delete and *IfMatch variants — instance-level CRUD
- Client.Transaction — submit a transaction Bundle
- Client.Operation — execute a generic server-defined $operation
- Client.Search / SearchPost / SearchPage / SearchAll / IterateSearch — type-level search with pagination
- Client.SearchBuilder — fluent query composition over url.Values
- Client.Metadata / CheckFHIRVersion / CheckFeatureSupport — capability helpers
- NewTransactionBundleBuilder / NewBatchBundleBuilder — assemble request bundles
Sub-clients (accessed via Client methods):
- Sync() *SyncClient — HAIStack sync push/pull over HTTP
- SMART() *SMARTClient — discovery, auth-code+PKCE, backend client assertion
- BulkExport() *BulkExportClient — kickoff, poll, cancel, manifest retrieval
- Subscriptions() *SubscriptionClient — standard FHIR Subscription REST helpers
Typed convenience (optional wrappers):
- ForResource(type) *ResourceClient
- Patient() / Observation() / Encounter() *ResourceClient
Configuration and infrastructure:
- Config — BaseURL, BasePath, HTTPClient, Codec, TokenProvider, RetryPolicy
- TokenProvider — AuthorizationHeader per request
- RetryPolicy / DefaultRetryPolicy — retryability, attempts, backoff, jitter
- Error — HTTP status, raw body, OperationOutcome, retry hints
Supported FHIR endpoints (v1) ¶
Base path defaults to /fhir (configurable via Config.BasePath).
- GET /fhir/metadata — CapabilityStatement
- POST /fhir — transaction or batch Bundle
- GET/POST /fhir/$operation — generic system operation
- GET/POST /fhir/{ResourceType}[/{id}]/$operation — generic operation
- GET /fhir/{ResourceType} — type-level search (searchset Bundle)
- POST /fhir/{ResourceType}/_search — form-encoded search
- POST /fhir/{ResourceType} — create
- POST /fhir/{ResourceType} — conditional create via If-None-Exist
- GET /fhir/{ResourceType}/{id} — read
- PUT /fhir/{ResourceType}/{id} — update
- PATCH /fhir/{ResourceType}/{id} — JSON Patch update
- DELETE /fhir/{ResourceType}/{id} — delete (204 No Content)
- PUT/DELETE /fhir/{ResourceType}?query — conditional update/delete
- GET /fhir/$export — bulk export kickoff (async)
- GET /fhir/Group/{id}/$export — group bulk export kickoff
Sync endpoints (HAIStack wire contract):
- POST /sync/push — propose LocalEvent batch
- GET /sync/pull?nodeId&tenantId&after — fetch CanonicalEvent batch
Configuration defaults ¶
- BasePath: /fhir
- Codec: types.NewJSONCodec()
- RetryPolicy: DefaultRetryPolicy (3 attempts, 250ms initial backoff)
- HTTPClient timeout: 30s when HTTPClient is nil
- FHIRVersion: 4.0.1 (R4) when server metadata unavailable
- UserAgent: haistack-client/1.0
Error handling ¶
Failures return *client.Error (use AsError to unwrap):
- StatusCode — HTTP response status
- Body — raw response bytes
- Outcome — parsed types.OperationOutcome when body is FHIR JSON
- Retryable — hint from RetryPolicy / status code classification
Retry behavior ¶
DefaultRetryPolicy retries on:
- Transport errors (network failures, timeouts)
- HTTP 429 Too Many Requests
- HTTP 5xx server errors
4xx responses are not retried unless RetryableStatus overrides are configured.
Typical usage ¶
c, err := client.New(client.Config{
BaseURL: "https://fhir.example.com",
TokenProvider: client.StaticTokenProvider{Token: accessToken},
})
// CRUD
created, err := c.Create(ctx, envelope)
read, err := c.Read(ctx, "Patient", "p1")
// Search with auto-pagination
all, err := c.SearchBuilder("Patient").Param("family", "Smith").SearchAll(ctx)
// Sync bridge for pkg/sync.Engine
pushResp, err := c.Sync().Push(ctx, client.ToPushRequest(nodeID, tenantID, events))
pullResp, err := c.Sync().Pull(ctx, client.PullRequest{NodeID: nodeID, TenantID: tenantID, After: cursor})
// SMART auth-code + PKCE
cfg, _ := c.SMART().Discover(ctx, issuer)
pkce, _ := client.NewPKCEChallenge()
authURL, _ := c.SMART().BuildAuthURL(client.AuthCodeRequest{...})
tokens, _ := c.SMART().ExchangeAuthCode(ctx, client.AuthCodeExchangeRequest{
TokenEndpoint: cfg.TokenEndpoint, ClientID: clientID, RedirectURI: redirectURI, Code: code, PKCE: pkce,
})
Out of scope (v1) ¶
- R5-specific typed surfaces
- HAIStack-private subscription delivery/admin APIs
- Automatic sync scheduling/runtime orchestration (use pkg/sync.Engine)
- Generated typed models for every FHIR resource
- OAuth authorization server implementation
- Server-side bulk export implementation (the client supports kickoff/poll)
See README.md in this directory for endpoint tables, configuration reference, usage examples, and test guidance.
Index ¶
- Constants
- func FromPullResponse(resp *PullResponse) []sync.CanonicalEvent
- func FromPushResponse(resp *PushResponse) []sync.PushResult
- func JoinScopes(scopes ...string) (string, error)
- func NormalizeFHIRVersion(version string) string
- func ParseTokenClaims(token string) (smart.TokenClaims, error)
- func PatientObservationFiltered(category string) (string, error)
- type AuthCodeExchangeRequest
- type AuthCodeRequest
- type BulkExportClient
- func (b *BulkExportClient) Cancel(ctx context.Context, statusURL string) error
- func (b *BulkExportClient) GetManifest(ctx context.Context, statusURL string) (*ExportManifest, error)
- func (b *BulkExportClient) Kickoff(ctx context.Context, req ExportKickoffRequest) (*ExportJob, error)
- func (b *BulkExportClient) PollStatus(ctx context.Context, statusURL string) (*ExportJob, error)
- func (b *BulkExportClient) Wait(ctx context.Context, statusURL string, interval time.Duration) (*ExportJob, error)
- func (b *BulkExportClient) WaitManifest(ctx context.Context, statusURL string, interval time.Duration) (*ExportJob, *ExportManifest, error)
- type BundleBuilder
- func (b *BundleBuilder) Build(codec types.ResourceCodec) (*types.ResourceEnvelope, error)
- func (b *BundleBuilder) CreateEntry(resource *types.ResourceEnvelope) *BundleBuilder
- func (b *BundleBuilder) DeleteEntry(resourceType, id string) *BundleBuilder
- func (b *BundleBuilder) IfMatch(versionID string) *BundleBuilder
- func (b *BundleBuilder) ReadEntry(resourceType, id string) *BundleBuilder
- func (b *BundleBuilder) Submit(ctx context.Context, c *Client) (*types.ResourceEnvelope, error)
- func (b *BundleBuilder) UpdateEntry(resource *types.ResourceEnvelope) *BundleBuilder
- type CapabilityMetadata
- type Client
- func (c *Client) BasePath() string
- func (c *Client) BaseURL() string
- func (c *Client) Batch(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (c *Client) BulkExport() *BulkExportClient
- func (c *Client) CheckFHIRVersion(ctx context.Context) (string, error)
- func (c *Client) CheckFeatureSupport(ctx context.Context, resourceType, interaction string) (bool, error)
- func (c *Client) Codec() types.ResourceCodec
- func (c *Client) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (c *Client) CreateConditional(ctx context.Context, resource *types.ResourceEnvelope, criteria url.Values) (*types.ResourceEnvelope, error)
- func (c *Client) CreateJSON(ctx context.Context, resourceType string, body []byte) ([]byte, error)
- func (c *Client) Delete(ctx context.Context, resourceType, id string) error
- func (c *Client) DeleteConditional(ctx context.Context, resourceType string, criteria url.Values) error
- func (c *Client) DeleteIfMatch(ctx context.Context, resourceType, id, versionID string) error
- func (c *Client) Encounter() *ResourceClient
- func (c *Client) FHIRVersion() string
- func (c *Client) ForResource(resourceType string) *ResourceClient
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) IterateSearch(ctx context.Context, resourceType string, params map[string]string) *SearchIterator
- func (c *Client) Metadata(ctx context.Context) (*CapabilityMetadata, error)
- func (c *Client) Observation() *ResourceClient
- func (c *Client) Operation(ctx context.Context, resourceType, id, operation string, params url.Values, ...) (*types.ResourceEnvelope, error)
- func (c *Client) Patch(ctx context.Context, resourceType, id string, patchJSON []byte) (*types.ResourceEnvelope, error)
- func (c *Client) PatchIfMatch(ctx context.Context, resourceType, id string, patchJSON []byte, ...) (*types.ResourceEnvelope, error)
- func (c *Client) Patient() *ResourceClient
- func (c *Client) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
- func (c *Client) ReadJSON(ctx context.Context, resourceType, id string) ([]byte, error)
- func (c *Client) SMART() *SMARTClient
- func (c *Client) Search(ctx context.Context, resourceType string, params map[string]string) (*SearchResult, error)
- func (c *Client) SearchAll(ctx context.Context, resourceType string, params map[string]string) ([]*types.ResourceEnvelope, error)
- func (c *Client) SearchBuilder(resourceType string) *SearchBuilder
- func (c *Client) SearchPage(ctx context.Context, resourceType, pageURL string) (*SearchResult, error)
- func (c *Client) SearchPost(ctx context.Context, resourceType string, params map[string]string) (*SearchResult, error)
- func (c *Client) Subscriptions() *SubscriptionClient
- func (c *Client) Sync() *SyncClient
- func (c *Client) Transaction(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (c *Client) Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (c *Client) UpdateConditional(ctx context.Context, resource *types.ResourceEnvelope, criteria url.Values) (*types.ResourceEnvelope, error)
- func (c *Client) UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, versionID string) (*types.ResourceEnvelope, error)
- func (c *Client) UpdateJSON(ctx context.Context, resourceType, id string, body []byte) ([]byte, error)
- type ClientAssertionRequest
- type ClientJWTAuth
- type Config
- type DefaultRetryPolicy
- type Error
- type ExportErrorFile
- type ExportJob
- type ExportJobStatus
- type ExportKickoffRequest
- type ExportManifest
- type ExportOutputFile
- type HeaderTokenProvider
- type PKCEChallenge
- type PullRequest
- type PullResponse
- type PushRequest
- type PushResponse
- type RefreshTokenRequest
- type ResourceCapability
- type ResourceClient
- func (r *ResourceClient) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (r *ResourceClient) CreateJSON(ctx context.Context, body []byte) ([]byte, error)
- func (r *ResourceClient) Delete(ctx context.Context, id string) error
- func (r *ResourceClient) DeleteIfMatch(ctx context.Context, id, versionID string) error
- func (r *ResourceClient) Patch(ctx context.Context, id string, patchJSON []byte) (*types.ResourceEnvelope, error)
- func (r *ResourceClient) PatchIfMatch(ctx context.Context, id string, patchJSON []byte, versionID string) (*types.ResourceEnvelope, error)
- func (r *ResourceClient) Read(ctx context.Context, id string) (*types.ResourceEnvelope, error)
- func (r *ResourceClient) ReadJSON(ctx context.Context, id string) ([]byte, error)
- func (r *ResourceClient) ResourceType() string
- func (r *ResourceClient) Search(ctx context.Context, params map[string]string) (*SearchResult, error)
- func (r *ResourceClient) SearchAll(ctx context.Context, params map[string]string) ([]*types.ResourceEnvelope, error)
- func (r *ResourceClient) SearchBuilder() *SearchBuilder
- func (r *ResourceClient) Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (r *ResourceClient) UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, versionID string) (*types.ResourceEnvelope, error)
- func (r *ResourceClient) UpdateJSON(ctx context.Context, id string, body []byte) ([]byte, error)
- type RetryPolicy
- type RevokeTokenRequest
- type SMARTClient
- func (s *SMARTClient) BuildAuthURL(req AuthCodeRequest) (string, error)
- func (s *SMARTClient) Discover(ctx context.Context, issuer string) (*SMARTConfiguration, error)
- func (s *SMARTClient) ExchangeAuthCode(ctx context.Context, req AuthCodeExchangeRequest) (*TokenResponse, error)
- func (s *SMARTClient) ExchangeClientAssertion(ctx context.Context, req ClientAssertionRequest) (*TokenResponse, error)
- func (s *SMARTClient) RefreshToken(ctx context.Context, req RefreshTokenRequest) (*TokenResponse, error)
- func (s *SMARTClient) RevokeToken(ctx context.Context, req RevokeTokenRequest) error
- type SMARTConfiguration
- type ScopeBuilder
- type ScopeSet
- type ScopedSyncClient
- type SearchBuilder
- func (b *SearchBuilder) AddParam(name, value string) *SearchBuilder
- func (b *SearchBuilder) Count(n int) *SearchBuilder
- func (b *SearchBuilder) OrParam(name string, values ...string) *SearchBuilder
- func (b *SearchBuilder) Param(name, value string) *SearchBuilder
- func (b *SearchBuilder) Search(ctx context.Context) (*SearchResult, error)
- func (b *SearchBuilder) SearchAll(ctx context.Context) ([]*types.ResourceEnvelope, error)
- func (b *SearchBuilder) Sort(fields ...string) *SearchBuilder
- func (b *SearchBuilder) Values() url.Values
- type SearchIterator
- type SearchResult
- type StaticTokenProvider
- type SubscriptionClient
- func (s *SubscriptionClient) Create(ctx context.Context, subscription *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- func (s *SubscriptionClient) Delete(ctx context.Context, id string) error
- func (s *SubscriptionClient) PollStatus(ctx context.Context, statusURL string) (*types.ResourceEnvelope, error)
- func (s *SubscriptionClient) Read(ctx context.Context, id string) (*types.ResourceEnvelope, error)
- func (s *SubscriptionClient) Search(ctx context.Context, params map[string]string) (*SearchResult, error)
- func (s *SubscriptionClient) SearchAll(ctx context.Context, params map[string]string) ([]*types.ResourceEnvelope, error)
- func (s *SubscriptionClient) Update(ctx context.Context, subscription *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
- type SyncClient
- type TokenProvider
- type TokenResponse
Constants ¶
const ( ClientAuthSecretPost = "client_secret_post" ClientAuthSecretBasic = "client_secret_basic" ClientAuthPrivateKeyJWT = "private_key_jwt" )
Variables ¶
This section is empty.
Functions ¶
func FromPullResponse ¶
func FromPullResponse(resp *PullResponse) []sync.CanonicalEvent
FromPullResponse returns canonical events from a pull response.
func FromPushResponse ¶
func FromPushResponse(resp *PushResponse) []sync.PushResult
FromPushResponse returns push results compatible with pkg/sync.Engine expectations.
func JoinScopes ¶
JoinScopes joins validated scope strings.
func NormalizeFHIRVersion ¶
NormalizeFHIRVersion maps common version strings to a comparable form.
func ParseTokenClaims ¶
func ParseTokenClaims(token string) (smart.TokenClaims, error)
ParseTokenClaims parses token claims without verification (caller validates separately).
func PatientObservationFiltered ¶
PatientObservationFiltered builds patient/Observation.rs?param=value.
Types ¶
type AuthCodeExchangeRequest ¶
type AuthCodeExchangeRequest struct {
TokenEndpoint string
ClientID string
ClientSecret string
ClientAuth string
ClientJWT *ClientJWTAuth
RedirectURI string
Code string
PKCE *PKCEChallenge
}
AuthCodeExchangeRequest exchanges an authorization code for tokens.
type AuthCodeRequest ¶
type AuthCodeRequest struct {
Config *SMARTConfiguration
ClientID string
RedirectURI string
Scope string
State string
PKCE *PKCEChallenge
Launch string
Aud string
ExtraParams map[string]string
}
AuthCodeRequest builds an authorization URL for the auth-code+PKCE flow.
type BulkExportClient ¶
type BulkExportClient struct {
// contains filtered or unexported fields
}
BulkExportClient supports standard FHIR bulk export patterns.
func (*BulkExportClient) Cancel ¶
func (b *BulkExportClient) Cancel(ctx context.Context, statusURL string) error
Cancel cancels an in-progress bulk export job.
func (*BulkExportClient) GetManifest ¶
func (b *BulkExportClient) GetManifest(ctx context.Context, statusURL string) (*ExportManifest, error)
GetManifest retrieves and parses the export manifest from a completed job status URL.
func (*BulkExportClient) Kickoff ¶
func (b *BulkExportClient) Kickoff(ctx context.Context, req ExportKickoffRequest) (*ExportJob, error)
Kickoff starts a system-level or group bulk export.
func (*BulkExportClient) PollStatus ¶
PollStatus checks the status of a bulk export job.
func (*BulkExportClient) Wait ¶
func (b *BulkExportClient) Wait(ctx context.Context, statusURL string, interval time.Duration) (*ExportJob, error)
Wait polls until the export reaches a terminal state or the context is cancelled.
func (*BulkExportClient) WaitManifest ¶
func (b *BulkExportClient) WaitManifest(ctx context.Context, statusURL string, interval time.Duration) (*ExportJob, *ExportManifest, error)
WaitManifest waits for completion and fetches the completed export manifest.
type BundleBuilder ¶
type BundleBuilder struct {
// contains filtered or unexported fields
}
BundleBuilder assembles transaction or batch request bundles.
func NewBatchBundleBuilder ¶
func NewBatchBundleBuilder() *BundleBuilder
NewBatchBundleBuilder returns a builder for batch bundles.
func NewTransactionBundleBuilder ¶
func NewTransactionBundleBuilder() *BundleBuilder
NewTransactionBundleBuilder returns a builder for transaction bundles.
func (*BundleBuilder) Build ¶
func (b *BundleBuilder) Build(codec types.ResourceCodec) (*types.ResourceEnvelope, error)
Build returns a Bundle ResourceEnvelope ready for submission.
func (*BundleBuilder) CreateEntry ¶
func (b *BundleBuilder) CreateEntry(resource *types.ResourceEnvelope) *BundleBuilder
CreateEntry adds a POST create entry.
func (*BundleBuilder) DeleteEntry ¶
func (b *BundleBuilder) DeleteEntry(resourceType, id string) *BundleBuilder
DeleteEntry adds a DELETE entry.
func (*BundleBuilder) IfMatch ¶
func (b *BundleBuilder) IfMatch(versionID string) *BundleBuilder
IfMatch sets If-Match on the last entry (for conditional updates).
func (*BundleBuilder) ReadEntry ¶
func (b *BundleBuilder) ReadEntry(resourceType, id string) *BundleBuilder
ReadEntry adds a GET read entry.
func (*BundleBuilder) Submit ¶
func (b *BundleBuilder) Submit(ctx context.Context, c *Client) (*types.ResourceEnvelope, error)
Submit builds and submits the bundle as a transaction.
func (*BundleBuilder) UpdateEntry ¶
func (b *BundleBuilder) UpdateEntry(resource *types.ResourceEnvelope) *BundleBuilder
UpdateEntry adds a PUT update entry.
type CapabilityMetadata ¶
type CapabilityMetadata struct {
FHIRVersion string
Formats []string
Resources []ResourceCapability
Raw []byte
}
CapabilityMetadata holds parsed CapabilityStatement fields.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the generic-first FHIR REST SDK.
func (*Client) Batch ¶
func (c *Client) Batch(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Batch submits a batch bundle and returns its batch-response Bundle.
func (*Client) BulkExport ¶
func (c *Client) BulkExport() *BulkExportClient
BulkExport returns the FHIR bulk export sub-client.
func (*Client) CheckFHIRVersion ¶
CheckFHIRVersion returns the server's advertised FHIR version, or the client default.
func (*Client) CheckFeatureSupport ¶
func (c *Client) CheckFeatureSupport(ctx context.Context, resourceType, interaction string) (bool, error)
CheckFeatureSupport reports whether the server advertises a resource interaction.
func (*Client) Codec ¶
func (c *Client) Codec() types.ResourceCodec
Codec returns the resource codec.
func (*Client) Create ¶
func (c *Client) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Create posts a new resource and returns the server-assigned envelope.
func (*Client) CreateConditional ¶
func (c *Client) CreateConditional(ctx context.Context, resource *types.ResourceEnvelope, criteria url.Values) (*types.ResourceEnvelope, error)
CreateConditional performs conditional create using the FHIR If-None-Exist header.
func (*Client) CreateJSON ¶
CreateJSON creates a resource from raw FHIR JSON and returns raw response JSON.
func (*Client) DeleteConditional ¶
func (c *Client) DeleteConditional(ctx context.Context, resourceType string, criteria url.Values) error
DeleteConditional deletes the single resource selected by search criteria.
func (*Client) DeleteIfMatch ¶
DeleteIfMatch deletes a resource only when versionID still matches the server's current weak ETag.
func (*Client) Encounter ¶
func (c *Client) Encounter() *ResourceClient
Encounter returns a convenience client for Encounter resources.
func (*Client) FHIRVersion ¶
FHIRVersion returns the default FHIR version target.
func (*Client) ForResource ¶
func (c *Client) ForResource(resourceType string) *ResourceClient
ForResource returns a typed convenience client for the given resource type.
func (*Client) HTTPClient ¶
HTTPClient returns the underlying HTTP client.
func (*Client) IterateSearch ¶
func (c *Client) IterateSearch(ctx context.Context, resourceType string, params map[string]string) *SearchIterator
IterateSearch returns a resource iterator for a type-level search.
func (*Client) Metadata ¶
func (c *Client) Metadata(ctx context.Context) (*CapabilityMetadata, error)
Metadata fetches the server CapabilityStatement.
func (*Client) Observation ¶
func (c *Client) Observation() *ResourceClient
Observation returns a convenience client for Observation resources.
func (*Client) Operation ¶
func (c *Client) Operation(ctx context.Context, resourceType, id, operation string, params url.Values, body []byte) (*types.ResourceEnvelope, error)
Operation executes a generic server-defined FHIR operation. A nil body uses GET; a non-nil body uses POST. The operation must include its leading '$'.
func (*Client) Patch ¶
func (c *Client) Patch(ctx context.Context, resourceType, id string, patchJSON []byte) (*types.ResourceEnvelope, error)
Patch applies an RFC 6902 JSON Patch to a resource.
func (*Client) PatchIfMatch ¶
func (c *Client) PatchIfMatch(ctx context.Context, resourceType, id string, patchJSON []byte, versionID string) (*types.ResourceEnvelope, error)
PatchIfMatch applies JSON Patch only when versionID still matches the server's current weak ETag.
func (*Client) Patient ¶
func (c *Client) Patient() *ResourceClient
Patient returns a convenience client for Patient resources.
func (*Client) Read ¶
func (c *Client) Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
Read fetches a resource by type and id.
func (*Client) SMART ¶
func (c *Client) SMART() *SMARTClient
SMART returns the SMART OAuth sub-client.
func (*Client) Search ¶
func (c *Client) Search(ctx context.Context, resourceType string, params map[string]string) (*SearchResult, error)
Search performs a type-level search with query parameters.
func (*Client) SearchAll ¶
func (c *Client) SearchAll(ctx context.Context, resourceType string, params map[string]string) ([]*types.ResourceEnvelope, error)
SearchAll auto-paginates through all search results.
func (*Client) SearchBuilder ¶
func (c *Client) SearchBuilder(resourceType string) *SearchBuilder
SearchBuilder returns a fluent search query builder for a resource type.
func (*Client) SearchPage ¶
func (c *Client) SearchPage(ctx context.Context, resourceType, pageURL string) (*SearchResult, error)
SearchPage fetches a search result from an absolute or relative next URL.
func (*Client) SearchPost ¶
func (c *Client) SearchPost(ctx context.Context, resourceType string, params map[string]string) (*SearchResult, error)
SearchPost performs a POST-based search using an URL-encoded parameter body.
func (*Client) Subscriptions ¶
func (c *Client) Subscriptions() *SubscriptionClient
Subscriptions returns the FHIR Subscription sub-client.
func (*Client) Sync ¶
func (c *Client) Sync() *SyncClient
Sync returns the HAIStack sync sub-client.
func (*Client) Transaction ¶
func (c *Client) Transaction(ctx context.Context, bundle *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Transaction submits a transaction bundle and returns the response bundle envelope.
func (*Client) Update ¶
func (c *Client) Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Update replaces a resource by type and id.
func (*Client) UpdateConditional ¶
func (c *Client) UpdateConditional(ctx context.Context, resource *types.ResourceEnvelope, criteria url.Values) (*types.ResourceEnvelope, error)
UpdateConditional replaces the single resource selected by search criteria.
func (*Client) UpdateIfMatch ¶
func (c *Client) UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, versionID string) (*types.ResourceEnvelope, error)
UpdateIfMatch replaces a resource only when versionID still matches the server's current weak ETag.
type ClientAssertionRequest ¶
type ClientAssertionRequest struct {
TokenEndpoint string
ClientID string
Scope string
PrivateKey *rsa.PrivateKey
KeyID string
Algorithm string
Audience string
Expiry time.Duration
}
ClientAssertionRequest builds a backend-service token exchange request.
type ClientJWTAuth ¶
type ClientJWTAuth struct {
PrivateKey *rsa.PrivateKey
KeyID string
Algorithm string
Expiry time.Duration
}
ClientJWTAuth configures private_key_jwt authentication at the token endpoint.
type Config ¶
type Config struct {
// BaseURL is the server origin, e.g. https://fhir.example.com.
BaseURL string
// BasePath is the FHIR REST prefix. Defaults to /fhir.
BasePath string
// HTTPClient is the underlying transport. A default client with Timeout is used when nil.
HTTPClient *http.Client
// Codec parses and serializes FHIR JSON. Defaults to types.NewJSONCodec().
Codec types.ResourceCodec
// TokenProvider supplies authorization headers per request.
TokenProvider TokenProvider
// RetryPolicy controls retryability, attempts, backoff, and jitter.
RetryPolicy RetryPolicy
// DefaultHeaders are added to every request (auth headers from TokenProvider take precedence).
DefaultHeaders map[string]string
// UserAgent overrides the default haistack-client user agent.
UserAgent string
// Timeout applies when HTTPClient is nil.
Timeout time.Duration
// FHIRVersion is the default interoperability target (R4). Used when server metadata is unavailable.
FHIRVersion string
}
Config configures a Client.
type DefaultRetryPolicy ¶
type DefaultRetryPolicy struct {
Attempts int
InitialDelay time.Duration
MaxDelay time.Duration
JitterFraction float64
// RetryableStatus overrides default retry classification for specific status codes.
RetryableStatus map[int]bool
}
DefaultRetryPolicy retries 429 and 5xx responses and transport errors.
func NewDefaultRetryPolicy ¶
func NewDefaultRetryPolicy() *DefaultRetryPolicy
NewDefaultRetryPolicy returns a policy with sensible defaults.
func (*DefaultRetryPolicy) Backoff ¶
func (p *DefaultRetryPolicy) Backoff(attempt int) time.Duration
Backoff implements RetryPolicy.
func (*DefaultRetryPolicy) MaxAttempts ¶
func (p *DefaultRetryPolicy) MaxAttempts() int
MaxAttempts implements RetryPolicy.
func (*DefaultRetryPolicy) ShouldRetry ¶
ShouldRetry implements RetryPolicy.
type Error ¶
type Error struct {
StatusCode int
Body []byte
Outcome *types.OperationOutcome
Retryable bool
Message string
}
Error carries HTTP status, raw body, parsed OperationOutcome, and retry hints.
func (*Error) IsRetryable ¶
IsRetryable reports whether the error is retryable.
type ExportErrorFile ¶
ExportErrorFile describes one error NDJSON file.
type ExportJob ¶
type ExportJob struct {
StatusURL string
Status ExportJobStatus
Progress string
TransactionTime time.Time
Request string
RequiresAccessToken bool
Raw []byte
}
ExportJob represents an in-flight or completed bulk export job.
type ExportJobStatus ¶
type ExportJobStatus string
ExportJobStatus tracks bulk export job state.
const ( ExportStatusInProgress ExportJobStatus = "in-progress" ExportStatusComplete ExportJobStatus = "complete" ExportStatusError ExportJobStatus = "error" ExportStatusCancelled ExportJobStatus = "cancelled" )
type ExportKickoffRequest ¶
type ExportKickoffRequest struct {
ResourceTypes []string
Since time.Time
GroupID string
OutputFormat string
TypeFilter string
}
ExportKickoffRequest configures a bulk export kickoff.
type ExportManifest ¶
type ExportManifest struct {
TransactionTime time.Time `json:"transactionTime"`
Request string `json:"request"`
RequiresAccessToken bool `json:"requiresAccessToken"`
Output []ExportOutputFile `json:"output"`
Error []ExportErrorFile `json:"error,omitempty"`
Raw []byte `json:"-"`
}
ExportManifest is the parsed export manifest.
type ExportOutputFile ¶
ExportOutputFile describes one exported NDJSON file.
type HeaderTokenProvider ¶
type HeaderTokenProvider struct {
Header string
}
HeaderTokenProvider returns a pre-built Authorization header value.
func (HeaderTokenProvider) AuthorizationHeader ¶
func (p HeaderTokenProvider) AuthorizationHeader(_ context.Context) (string, error)
AuthorizationHeader implements TokenProvider.
type PKCEChallenge ¶
PKCEChallenge holds a PKCE verifier/challenge pair.
func NewPKCEChallenge ¶
func NewPKCEChallenge() (*PKCEChallenge, error)
NewPKCEChallenge generates an S256 PKCE challenge.
type PullRequest ¶
type PullRequest struct {
NodeID string `json:"nodeId"`
TenantID string `json:"tenantId"`
After int64 `json:"after"`
Limit int `json:"limit,omitempty"`
}
PullRequest carries pull cursor parameters.
type PullResponse ¶
type PullResponse struct {
Events []sync.CanonicalEvent `json:"events"`
NextCursor int64 `json:"nextCursor"`
HasMore bool `json:"hasMore"`
}
PullResponse is the HTTP wire response for GET /sync/pull.
type PushRequest ¶
type PushRequest struct {
NodeID string `json:"nodeId"`
TenantID string `json:"tenantId"`
Events []sync.LocalEvent `json:"events"`
}
PushRequest is the HTTP wire payload for POST /sync/push.
func ToPushRequest ¶
func ToPushRequest(nodeID, tenantID string, events []sync.LocalEvent) PushRequest
ToPushRequest converts local events into a push request with explicit node and tenant IDs.
type PushResponse ¶
type PushResponse struct {
Results []sync.PushResult `json:"results"`
}
PushResponse is the HTTP wire response for POST /sync/push.
type RefreshTokenRequest ¶
type RefreshTokenRequest struct {
TokenEndpoint string
ClientID string
ClientSecret string
ClientAuth string
ClientJWT *ClientJWTAuth
RefreshToken string
}
RefreshTokenRequest refreshes an access token when the server supports it.
type ResourceCapability ¶
ResourceCapability describes one supported resource type.
type ResourceClient ¶
type ResourceClient struct {
// contains filtered or unexported fields
}
ResourceClient provides typed convenience methods for one resource type.
func (*ResourceClient) Create ¶
func (r *ResourceClient) Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Create creates a resource of the bound type.
func (*ResourceClient) CreateJSON ¶
CreateJSON creates a bound resource from raw FHIR JSON.
func (*ResourceClient) Delete ¶
func (r *ResourceClient) Delete(ctx context.Context, id string) error
Delete deletes a resource of the bound type.
func (*ResourceClient) DeleteIfMatch ¶
func (r *ResourceClient) DeleteIfMatch(ctx context.Context, id, versionID string) error
DeleteIfMatch deletes a bound resource when its version still matches.
func (*ResourceClient) Patch ¶
func (r *ResourceClient) Patch(ctx context.Context, id string, patchJSON []byte) (*types.ResourceEnvelope, error)
Patch applies an RFC 6902 JSON Patch to the bound resource type.
func (*ResourceClient) PatchIfMatch ¶
func (r *ResourceClient) PatchIfMatch(ctx context.Context, id string, patchJSON []byte, versionID string) (*types.ResourceEnvelope, error)
PatchIfMatch applies JSON Patch to a bound resource when its version still matches.
func (*ResourceClient) Read ¶
func (r *ResourceClient) Read(ctx context.Context, id string) (*types.ResourceEnvelope, error)
Read reads a resource of the bound type.
func (*ResourceClient) ResourceType ¶
func (r *ResourceClient) ResourceType() string
ResourceType returns the bound resource type.
func (*ResourceClient) Search ¶
func (r *ResourceClient) Search(ctx context.Context, params map[string]string) (*SearchResult, error)
Search searches resources of the bound type.
func (*ResourceClient) SearchAll ¶
func (r *ResourceClient) SearchAll(ctx context.Context, params map[string]string) ([]*types.ResourceEnvelope, error)
SearchAll auto-paginates search results for the bound type.
func (*ResourceClient) SearchBuilder ¶
func (r *ResourceClient) SearchBuilder() *SearchBuilder
SearchBuilder returns a fluent search builder for the bound type.
func (*ResourceClient) Update ¶
func (r *ResourceClient) Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Update updates a resource of the bound type.
func (*ResourceClient) UpdateIfMatch ¶
func (r *ResourceClient) UpdateIfMatch(ctx context.Context, resource *types.ResourceEnvelope, versionID string) (*types.ResourceEnvelope, error)
UpdateIfMatch replaces a bound resource when its version still matches.
func (*ResourceClient) UpdateJSON ¶
UpdateJSON replaces a bound resource from raw FHIR JSON.
type RetryPolicy ¶
type RetryPolicy interface {
// ShouldRetry reports whether the request should be retried for the given attempt (0-based).
ShouldRetry(attempt int, resp *http.Response, err error) bool
// MaxAttempts returns the maximum number of attempts including the first.
MaxAttempts() int
// Backoff returns the delay before the next attempt.
Backoff(attempt int) time.Duration
}
RetryPolicy decides retryability, max attempts, backoff, and jitter.
type RevokeTokenRequest ¶
type RevokeTokenRequest struct {
RevocationEndpoint string
ClientID string
ClientSecret string
ClientAuth string
ClientJWT *ClientJWTAuth
Token string
TokenTypeHint string
}
RevokeTokenRequest revokes an access or refresh token when the server supports it.
type SMARTClient ¶
type SMARTClient struct {
// contains filtered or unexported fields
}
SMARTClient supports SMART discovery, auth-code+PKCE, and backend client assertion flows.
func (*SMARTClient) BuildAuthURL ¶
func (s *SMARTClient) BuildAuthURL(req AuthCodeRequest) (string, error)
BuildAuthURL constructs the authorization endpoint URL for auth-code+PKCE.
func (*SMARTClient) Discover ¶
func (s *SMARTClient) Discover(ctx context.Context, issuer string) (*SMARTConfiguration, error)
Discover fetches SMART configuration from the issuer.
func (*SMARTClient) ExchangeAuthCode ¶
func (s *SMARTClient) ExchangeAuthCode(ctx context.Context, req AuthCodeExchangeRequest) (*TokenResponse, error)
ExchangeAuthCode exchanges an authorization code for tokens.
func (*SMARTClient) ExchangeClientAssertion ¶
func (s *SMARTClient) ExchangeClientAssertion(ctx context.Context, req ClientAssertionRequest) (*TokenResponse, error)
ExchangeClientAssertion exchanges a backend-service client assertion for tokens.
func (*SMARTClient) RefreshToken ¶
func (s *SMARTClient) RefreshToken(ctx context.Context, req RefreshTokenRequest) (*TokenResponse, error)
RefreshToken refreshes an access token when the server supports it.
func (*SMARTClient) RevokeToken ¶
func (s *SMARTClient) RevokeToken(ctx context.Context, req RevokeTokenRequest) error
RevokeToken revokes an access or refresh token when the server supports it.
type SMARTConfiguration ¶
type SMARTConfiguration struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
CodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"`
Raw []byte `json:"-"`
}
SMARTConfiguration is parsed from .well-known/smart-configuration.
type ScopeBuilder ¶
type ScopeBuilder struct {
Actor smart.ActorClass
Resource string
Letters string
Filters url.Values
}
ScopeBuilder constructs SMART 2.2 CRUDS scope strings.
func (ScopeBuilder) String ¶
func (b ScopeBuilder) String() string
ReadSearch returns a patient/Observation.rs style scope.
type ScopeSet ¶
ScopeSet is a validated SMART scope set for outbound authorize/token requests.
func ParseScopes ¶
ParseScopes validates and normalizes SMART 1.x and 2.2 scope strings.
type ScopedSyncClient ¶
type ScopedSyncClient struct {
// contains filtered or unexported fields
}
ScopedSyncClient binds node and tenant identity once for repeated sync calls, while the wire protocol continues to send both fields explicitly.
func (*ScopedSyncClient) Pull ¶
func (s *ScopedSyncClient) Pull(ctx context.Context, after int64, limit int) (*PullResponse, error)
func (*ScopedSyncClient) Push ¶
func (s *ScopedSyncClient) Push(ctx context.Context, events []sync.LocalEvent) (*PushResponse, error)
type SearchBuilder ¶
type SearchBuilder struct {
// contains filtered or unexported fields
}
SearchBuilder composes FHIR search query parameters fluently.
func (*SearchBuilder) AddParam ¶
func (b *SearchBuilder) AddParam(name, value string) *SearchBuilder
AddParam appends a repeated search parameter value.
func (*SearchBuilder) Count ¶
func (b *SearchBuilder) Count(n int) *SearchBuilder
Count sets _count.
func (*SearchBuilder) OrParam ¶
func (b *SearchBuilder) OrParam(name string, values ...string) *SearchBuilder
OrParam sets a comma-separated OR value for a parameter.
func (*SearchBuilder) Param ¶
func (b *SearchBuilder) Param(name, value string) *SearchBuilder
Param sets a single-valued search parameter.
func (*SearchBuilder) Search ¶
func (b *SearchBuilder) Search(ctx context.Context) (*SearchResult, error)
Search executes the built query.
func (*SearchBuilder) SearchAll ¶
func (b *SearchBuilder) SearchAll(ctx context.Context) ([]*types.ResourceEnvelope, error)
SearchAll auto-paginates the built query.
func (*SearchBuilder) Sort ¶
func (b *SearchBuilder) Sort(fields ...string) *SearchBuilder
Sort sets _sort.
func (*SearchBuilder) Values ¶
func (b *SearchBuilder) Values() url.Values
Values returns the composed url.Values.
type SearchIterator ¶
type SearchIterator struct {
// contains filtered or unexported fields
}
SearchIterator walks resources across search pages while retaining the underlying page metadata for callers that need it.
func (*SearchIterator) Err ¶
func (it *SearchIterator) Err() error
Err returns the terminal iterator error, if any.
func (*SearchIterator) Next ¶
func (it *SearchIterator) Next() bool
Next advances the iterator to the next resource.
func (*SearchIterator) Resource ¶
func (it *SearchIterator) Resource() *types.ResourceEnvelope
Resource returns the resource selected by the most recent successful Next.
type SearchResult ¶
type SearchResult struct {
ResourceType string
Entries []*types.ResourceEnvelope
Total *int
NextURL string
SelfURL string
RawBundle []byte
}
SearchResult is a page-aware search result with bundle metadata.
func (*SearchResult) HasNext ¶
func (r *SearchResult) HasNext() bool
HasNext reports whether another page is available.
type StaticTokenProvider ¶
type StaticTokenProvider struct {
Token string
}
StaticTokenProvider returns a fixed bearer token.
func (StaticTokenProvider) AuthorizationHeader ¶
func (p StaticTokenProvider) AuthorizationHeader(_ context.Context) (string, error)
AuthorizationHeader implements TokenProvider.
type SubscriptionClient ¶
type SubscriptionClient struct {
// contains filtered or unexported fields
}
SubscriptionClient provides standard FHIR Subscription REST helpers.
func (*SubscriptionClient) Create ¶
func (s *SubscriptionClient) Create(ctx context.Context, subscription *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Create creates a Subscription resource.
func (*SubscriptionClient) Delete ¶
func (s *SubscriptionClient) Delete(ctx context.Context, id string) error
Delete deletes a Subscription by id.
func (*SubscriptionClient) PollStatus ¶
func (s *SubscriptionClient) PollStatus(ctx context.Context, statusURL string) (*types.ResourceEnvelope, error)
PollStatus polls a Subscription status endpoint when the server exposes one. statusURL may be absolute or relative to the client base URL.
func (*SubscriptionClient) Read ¶
func (s *SubscriptionClient) Read(ctx context.Context, id string) (*types.ResourceEnvelope, error)
Read reads a Subscription by id.
func (*SubscriptionClient) Search ¶
func (s *SubscriptionClient) Search(ctx context.Context, params map[string]string) (*SearchResult, error)
Search searches Subscription resources.
func (*SubscriptionClient) SearchAll ¶
func (s *SubscriptionClient) SearchAll(ctx context.Context, params map[string]string) ([]*types.ResourceEnvelope, error)
SearchAll auto-paginates Subscription search results.
func (*SubscriptionClient) Update ¶
func (s *SubscriptionClient) Update(ctx context.Context, subscription *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
Update updates a Subscription resource.
type SyncClient ¶
type SyncClient struct {
// contains filtered or unexported fields
}
SyncClient provides HAIStack sync push/pull over HTTP.
func (*SyncClient) For ¶
func (s *SyncClient) For(nodeID, tenantID string) (*ScopedSyncClient, error)
func (*SyncClient) Pull ¶
func (s *SyncClient) Pull(ctx context.Context, req PullRequest) (*PullResponse, error)
Pull fetches canonical events after a cursor.
func (*SyncClient) Push ¶
func (s *SyncClient) Push(ctx context.Context, req PushRequest) (*PushResponse, error)
Push submits local events to the sync hub.
type TokenProvider ¶
type TokenProvider interface {
// AuthorizationHeader returns the full Authorization header value, e.g. "Bearer <token>".
// Return empty string when no auth is required for the request.
AuthorizationHeader(ctx context.Context) (string, error)
}
TokenProvider supplies authorization headers for outbound requests.
func TokenProviderFromResponse ¶
func TokenProviderFromResponse(resp *TokenResponse) TokenProvider
TokenProviderFromResponse returns a TokenProvider backed by a token response.
type TokenResponse ¶
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in,omitempty"`
Scope string `json:"scope,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
Patient string `json:"patient,omitempty"`
Encounter string `json:"encounter,omitempty"`
Raw []byte `json:"-"`
}
TokenResponse is a parsed OAuth2 token response.