client

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

README

haistack-client (pkg/client)

Generic-first Go SDK for FHIR REST and HAIStack sync endpoints.

What it does

haistack-client is the outbound HTTP SDK for HAIStack. It mirrors the FHIR REST surface exposed by pkg/http and adds focused sub-clients for sync, SMART, bulk export, and subscriptions.

Think of it as the client-side inverse of the server adapter:

Concern Owner
HTTP request construction and retries pkg/client
Auth header injection (TokenProvider) pkg/client
OperationOutcome error parsing pkg/client
CRUD, search, bundles, metadata pkg/client
HAIStack sync HTTP wire contract pkg/client
SMART discovery, PKCE, client assertion (outbound) pkg/client
FHIR bulk export kickoff/poll/manifest pkg/client
FHIR Subscription REST helpers pkg/client
FHIR JSON envelopes and codecs pkg/types
Sync protocol models (transport-agnostic) pkg/sync
FHIR REST server adapter pkg/http
SMART token validation (server-side) pkg/smart
Resource lifecycle and persistence pkg/core
Search planning and execution pkg/search

It does not:

  • Open databases or manage tenants (pkg/sqlite, pkg/postgres)
  • Run sync scheduling or orchestration (pkg/sync Engine)
  • Validate inbound SMART tokens (pkg/smart — use that on the server)
  • Implement an OAuth authorization server
  • Generate typed models for every FHIR resource

When to use it

  • Building Go applications, CLIs, or device agents that call a HAIStack FHIR server
  • Bridging pkg/sync.Engine to a remote hub over HTTP push/pull
  • Exchanging SMART tokens (auth-code+PKCE or backend client assertion) and attaching them to FHIR requests
  • Integration tests that exercise outbound FHIR REST against httptest or real servers
  • Bulk export workflows against standard FHIR bulk data endpoints

Design

  • Envelope-first: CRUD and search return types.ResourceEnvelope with normalized FHIR JSON.
  • Typed helpers are optional: Patient(), Observation(), Encounter(), and ForResource() are thin wrappers — the generic API is primary.
  • R4 default: FHIR version defaults to 4.0.1 unless server metadata advertises otherwise.
  • Sync boundary: SyncClient owns HTTP transport; pkg/sync models are reused on the wire.
  • Explicit sync metadata: nodeId and tenantId are required on every push/pull request.

Supported endpoints

FHIR REST

Base path defaults to /fhir (configurable via Config.BasePath).

Method Path Action Success
GET /fhir/metadata Server capability statement 200 + CapabilityStatement
POST /fhir Transaction bundle 200 + transaction-response Bundle
POST /fhir Batch bundle 200 + batch-response Bundle
GET/POST /fhir/$operation or resource operation path Generic custom operation 200 + returned resource
GET /fhir/{ResourceType} Type-level search 200 + searchset Bundle
POST /fhir/{ResourceType}/_search Form-encoded search 200 + searchset Bundle
POST /fhir/{ResourceType} Create resource 201 + resource
POST /fhir/{ResourceType} + If-None-Exist Conditional create 201/200 + resource
GET /fhir/{ResourceType}/{id} Read resource 200 + resource
PUT /fhir/{ResourceType}/{id} Update resource 200 + resource
PATCH /fhir/{ResourceType}/{id} JSON Patch update 200 + resource
DELETE /fhir/{ResourceType}/{id} Delete resource 204 No Content
PUT/DELETE /fhir/{ResourceType}?criteria Conditional update/delete 201/200/204
GET /fhir/$export System bulk export kickoff 501 until server implements bulk export
GET /fhir/Group/{id}/$export Group bulk export kickoff 501 until server implements bulk export
HAIStack sync (wire contract)
Method Path Action Success
POST /sync/push Propose LocalEvent batch 200 + PushResult per event
GET /sync/pull Fetch CanonicalEvent batch 200 + events + cursor

Pull query parameters: nodeId, tenantId, after (cursor), limit (optional).

Deferred (v1)
  • Bulk export server implementation (client supports kickoff/poll; servers return 501 today)
  • R5-specific typed surfaces
  • HAIStack-private subscription delivery/admin APIs

Usage

Construct a client
import (
    "context"
    "log"
    "time"

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

c, err := client.New(client.Config{
    BaseURL:       "https://fhir.example.com",
    BasePath:      "/fhir", // default
    TokenProvider: client.StaticTokenProvider{Token: accessToken},
    RetryPolicy: &client.DefaultRetryPolicy{
        Attempts:     5,
        InitialDelay: 500 * time.Millisecond,
        MaxDelay:     30 * time.Second,
    },
    DefaultHeaders: map[string]string{
        "X-Request-Source": "my-app",
    },
})
if err != nil {
    log.Fatal(err)
}

Use a custom TokenProvider when tokens refresh or vary per request:

type refreshingProvider struct {
    smart *client.SMARTClient
    // ...
}

func (p *refreshingProvider) AuthorizationHeader(ctx context.Context) (string, error) {
  // Return "Bearer <token>" or empty when unauthenticated
}
CRUD
import (
    "github.com/degoke/haistack/pkg/types"
)

codec := types.NewJSONCodec()
env, err := codec.ParseJSON("Patient", []byte(`{"resourceType":"Patient","name":[{"family":"Smith"}]}`))
if err != nil {
    log.Fatal(err)
}

created, err := c.Create(ctx, env)
read, err := c.Read(ctx, "Patient", created.ID)

env.ID = created.ID
updated, err := c.Update(ctx, env)
err = c.Delete(ctx, "Patient", created.ID)
Search and pagination
// Single page
result, err := c.Search(ctx, "Patient", map[string]string{"family": "Smith"})
if result.HasNext() {
    next, err := c.SearchPage(ctx, "Patient", result.NextURL)
}

// Auto-pagination across all pages
all, err := c.SearchAll(ctx, "Patient", map[string]string{"family": "Smith"})

// Fluent builder with repeated params, OR values, _count, _sort
patients, err := c.SearchBuilder("Patient").
    Param("family", "Smith").
    AddParam("identifier", "mrn-1").
    OrParam("gender", "male", "female").
    Count(100).
    Sort("family", "-birthdate").
    SearchAll(ctx)

SearchResult exposes Entries, Total, NextURL, SelfURL, and RawBundle for advanced use.

Transaction bundles
bundle, err := client.NewTransactionBundleBuilder().
    CreateEntry(patientEnvelope).
    UpdateEntry(observationEnvelope).
    DeleteEntry("Encounter", "enc-1").
    Submit(ctx, c)
Capability and version checks
meta, err := c.Metadata(ctx)
version, err := c.CheckFHIRVersion(ctx)

supported, err := c.CheckFeatureSupport(ctx, "Patient", "search-type")
Sync push/pull

Bridge pkg/sync.Engine to a remote hub. Request metadata includes node and tenant IDs explicitly:

import "github.com/degoke/haistack/pkg/sync"

pushResp, err := c.Sync().Push(ctx, client.PushRequest{
    NodeID:   "device-node-1",
    TenantID: "tenant-a",
    Events:   []sync.LocalEvent{event},
})
results := client.FromPushResponse(pushResp)

pullResp, err := c.Sync().Pull(ctx, client.PullRequest{
    NodeID:   "device-node-1",
    TenantID: "tenant-a",
    After:    cursor,
    Limit:    100,
})
events := client.FromPullResponse(pullResp)

Or use the helper:

pushResp, err := c.Sync().Push(ctx, client.ToPushRequest(nodeID, tenantID, events))
SMART auth-code + PKCE

Outbound OAuth for interactive apps. Server-side token validation remains in pkg/smart.

cfg, err := c.SMART().Discover(ctx, "https://fhir.example.com")
pkce, err := client.NewPKCEChallenge()

authURL, err := c.SMART().BuildAuthURL(client.AuthCodeRequest{
    Config:      cfg,
    ClientID:    "my-app",
    RedirectURI: "https://app.example/callback",
    Scope:       "launch/patient patient/*.read openid",
    State:       "csrf-token",
    PKCE:        pkce,
    Launch:      launchToken, // optional EHR launch context
})
// Redirect the user to authURL, capture the authorization code, then:
tokens, err := c.SMART().ExchangeAuthCode(ctx, client.AuthCodeExchangeRequest{
    TokenEndpoint: cfg.TokenEndpoint,
    ClientID:      "my-app",
    ClientSecret:  "optional-for-confidential-clients",
    ClientAuth:    client.ClientAuthSecretPost, // or ClientAuthSecretBasic or ClientAuthPrivateKeyJWT
    RedirectURI:   "https://app.example/callback",
    Code:          code,
    PKCE:          pkce,
})

// private_key_jwt confidential clients:
tokens, err = c.SMART().ExchangeAuthCode(ctx, client.AuthCodeExchangeRequest{
    TokenEndpoint: cfg.TokenEndpoint,
    ClientID:      "my-jwt-app",
    ClientAuth:    client.ClientAuthPrivateKeyJWT,
    ClientJWT:     &client.ClientJWTAuth{PrivateKey: rsaPrivateKey},
    RedirectURI:   "https://app.example/callback",
    Code:          code,
    PKCE:          pkce,
})

// Attach token to FHIR requests
c, _ = client.New(client.Config{
    BaseURL:       "https://fhir.example.com",
    TokenProvider: client.TokenProviderFromResponse(tokens),
})

Refresh when supported:

refreshed, err := c.SMART().RefreshToken(ctx, client.RefreshTokenRequest{
    TokenEndpoint: cfg.TokenEndpoint,
    ClientID:      "my-app",
    ClientSecret:  "optional-for-confidential-clients",
    ClientAuth:    client.ClientAuthSecretBasic,
    RefreshToken:  tokens.RefreshToken,
})

err = c.SMART().RevokeToken(ctx, client.RevokeTokenRequest{
    RevocationEndpoint: cfg.RevocationEndpoint,
    ClientID:           "my-app",
    ClientSecret:       "optional-for-confidential-clients",
    Token:              tokens.AccessToken,
    TokenTypeHint:      "access_token",
})
SMART backend client assertion

For system/service accounts using signed JWT assertions:

tokens, err := c.SMART().ExchangeClientAssertion(ctx, client.ClientAssertionRequest{
    TokenEndpoint: cfg.TokenEndpoint,
    ClientID:      "backend-app",
    Scope:         "system/*.read",
    PrivateKey:    rsaPrivateKey,
    KeyID:         "key-1",
    Audience:      cfg.TokenEndpoint,
})

Parse claims without verification (validate separately with pkg/smart on the server):

claims, err := client.ParseTokenClaims(tokens.AccessToken)
Bulk export

Standard FHIR bulk data export (async):

job, err := c.BulkExport().Kickoff(ctx, client.ExportKickoffRequest{
    ResourceTypes: []string{"Patient", "Observation"},
    Since:         time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
    OutputFormat:  "application/fhir+ndjson",
})

// Poll until complete
completed, err := c.BulkExport().Wait(ctx, job.StatusURL, 5*time.Second)

// Or poll manually
status, err := c.BulkExport().PollStatus(ctx, job.StatusURL)

// Retrieve manifest when complete
manifest, err := c.BulkExport().GetManifest(ctx, job.StatusURL)
for _, file := range manifest.Output {
    // file.Type, file.URL — NDJSON download URLs
}

// Cancel in-flight export
err = c.BulkExport().Cancel(ctx, job.StatusURL)
Subscriptions

Standard FHIR Subscription REST (not HAIStack-private delivery APIs):

sub, err := c.Subscriptions().Create(ctx, subscriptionEnvelope)
active, err := c.Subscriptions().Read(ctx, "sub-1")
err = c.Subscriptions().Delete(ctx, "sub-1")

results, err := c.Subscriptions().Search(ctx, map[string]string{"status": "active"})

// When server exposes a status endpoint
status, err := c.Subscriptions().PollStatus(ctx, "/fhir/Subscription/sub-1/$status")
Typed helpers (optional)

Convenience wrappers over the generic API — not required:

patient, err := c.Patient().Read(ctx, "p1")
obs, err := c.Observation().Search(ctx, map[string]string{"code": "8867-4"})
enc, err := c.Encounter().SearchAll(ctx, nil)

// Or bind any resource type
custom, err := c.ForResource("MedicationRequest").Read(ctx, "rx-1")

Configuration reference

Field Required Default Description
BaseURL yes — Server origin, e.g. https://fhir.example.com
BasePath no /fhir FHIR REST prefix
HTTPClient no 30s timeout client Underlying *http.Client
Codec no types.NewJSONCodec() FHIR JSON parse/serialize
TokenProvider no nil Authorization header per request
RetryPolicy no DefaultRetryPolicy Retry attempts, backoff, jitter
DefaultHeaders no nil Headers added to every request
UserAgent no haistack-client/1.0 User-Agent header
Timeout no 30s Applied when HTTPClient is nil
FHIRVersion no 4.0.1 Default when metadata unavailable

Error handling

Failures return *client.Error. Use client.AsError(err) to unwrap:

env, err := c.Read(ctx, "Patient", "missing")
if err != nil {
    if ce, ok := client.AsError(err); ok {
        log.Printf("status=%d retryable=%v", ce.StatusCode, ce.Retryable)
        if ce.Outcome != nil {
            for _, issue := range ce.Outcome.Issue {
                log.Printf("issue: %s — %s", issue.Code, issue.Diagnostics)
            }
        }
    }
}
Field Description
StatusCode HTTP response status
Body Raw response bytes
Outcome Parsed types.OperationOutcome when body is FHIR JSON
Retryable Whether the request pipeline classified this as retryable

Typical status mapping (aligned with pkg/http server behavior):

HTTP status Retryable (default) Notes
400 no Invalid request / query
401 no Missing or invalid credentials
403 no Authorization denied
404 no Resource not found
409 no Version conflict
429 yes Rate limited
5xx yes Server error

Retry behavior

DefaultRetryPolicy retries on transport errors, HTTP 429, and HTTP 5xx. Configure overrides:

policy := &client.DefaultRetryPolicy{
    Attempts:     5,
    InitialDelay: 500 * time.Millisecond,
    MaxDelay:     30 * time.Second,
    JitterFraction: 0.2,
    RetryableStatus: map[int]bool{
        408: true, // retry request timeout
    },
}

Implement RetryPolicy for fully custom behavior.

Package layout

File Role
client.go Client, New, sub-client accessors, typed helpers
config.go Config and defaults
request.go Shared request pipeline, retries, content types
errors.go Error, OperationOutcome parsing
retry.go RetryPolicy, DefaultRetryPolicy
auth.go TokenProvider implementations
resources.go CRUD, ResourceClient typed wrapper
search.go Search, SearchBuilder, pagination, SearchResult
bundle.go BundleBuilder for transaction/batch bundles
capability.go Metadata, CheckFHIRVersion, CheckFeatureSupport
sync.go SyncClient, push/pull DTOs, bridge helpers
smart.go SMART discovery, PKCE, token exchange, client assertion
bulk.go Bulk export kickoff, poll, wait, cancel, manifest
subscription.go Subscription CRUD/search/status polling

Testing

go test ./pkg/client/... -count=1
  • Unit tests — CRUD request construction, error mapping, search builder, sync serialization, SMART PKCE/assertion, bulk export state machine, subscription CRUD
  • Integration tests (integration_test.go) — end-to-end FHIR CRUD/search/pagination and sync over httptest.Server
Package Relationship
pkg/http Server-side FHIR REST adapter (inverse of this SDK)
pkg/types ResourceEnvelope, ResourceCodec, OperationOutcome
pkg/sync Transport-agnostic sync models; Engine orchestration
pkg/smart Server-side token/assertion validation and scope parsing
pkg/core Server-side resource lifecycle (not called by client)
pkg/search Server-side search execution (not called by client)

See doc.go for API detail, defaults, and non-goals.

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

View Source
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

func JoinScopes(scopes ...string) (string, error)

JoinScopes joins validated scope strings.

func NormalizeFHIRVersion

func NormalizeFHIRVersion(version string) string

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

func PatientObservationFiltered(category string) (string, error)

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

Kickoff starts a system-level or group bulk export.

func (*BulkExportClient) PollStatus

func (b *BulkExportClient) PollStatus(ctx context.Context, statusURL string) (*ExportJob, error)

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

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

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 New

func New(cfg Config) (*Client, error)

New constructs a Client from Config.

func (*Client) BasePath

func (c *Client) BasePath() string

BasePath returns the configured FHIR REST prefix.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL returns the configured server origin.

func (*Client) Batch

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

func (c *Client) CheckFHIRVersion(ctx context.Context) (string, error)

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

func (c *Client) CreateJSON(ctx context.Context, resourceType string, body []byte) ([]byte, error)

CreateJSON creates a resource from raw FHIR JSON and returns raw response JSON.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, resourceType, id string) error

Delete removes a resource by type and id.

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

func (c *Client) DeleteIfMatch(ctx context.Context, resourceType, id, versionID string) error

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

func (c *Client) FHIRVersion() string

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

func (c *Client) HTTPClient() *http.Client

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

func (c *Client) ReadJSON(ctx context.Context, resourceType, id string) ([]byte, error)

ReadJSON reads a resource and returns raw response JSON.

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.

func (*Client) UpdateJSON

func (c *Client) UpdateJSON(ctx context.Context, resourceType, id string, body []byte) ([]byte, error)

UpdateJSON replaces a resource from raw FHIR JSON and returns raw response JSON.

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

func (p *DefaultRetryPolicy) ShouldRetry(attempt int, resp *http.Response, err error) bool

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 AsError

func AsError(err error) (*Error, bool)

AsError unwraps or wraps an error as *Error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) IsRetryable

func (e *Error) IsRetryable() bool

IsRetryable reports whether the error is retryable.

type ExportErrorFile

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

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

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

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

type PKCEChallenge struct {
	Verifier  string
	Challenge string
	Method    string
}

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

type ResourceCapability struct {
	Type         string
	Interactions []string
	SearchParams []string
}

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

Create creates a resource of the bound type.

func (*ResourceClient) CreateJSON

func (r *ResourceClient) CreateJSON(ctx context.Context, body []byte) ([]byte, error)

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

Read reads a resource of the bound type.

func (*ResourceClient) ReadJSON

func (r *ResourceClient) ReadJSON(ctx context.Context, id string) ([]byte, error)

ReadJSON reads a bound resource as raw FHIR JSON.

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

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

func (r *ResourceClient) UpdateJSON(ctx context.Context, id string, body []byte) ([]byte, error)

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

type ScopeSet = smart.ScopeSet

ScopeSet is a validated SMART scope set for outbound authorize/token requests.

func ParseScopes

func ParseScopes(raw string) (ScopeSet, error)

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

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

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

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.

Jump to

Keyboard shortcuts

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