server

package
v0.0.0-...-0828858 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2018 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// OK when returned by MongoDB is really a float (0.0 = false, 1.0 = true)
	OK = float64(1)
)

Variables

View Source
var Database *mgo.Database

Although we got rid of the global in the fhir package, the ie project still needs it Once ie removes the dependency on the global, this should go away

View Source
var DefaultConfig = Config{
	ServerURL:             "",
	IndexConfigPath:       "config/indexes.conf",
	DatabaseHost:          "localhost:27017",
	DatabaseName:          "fhir",
	DatabaseSocketTimeout: 2 * time.Minute,
	DatabaseOpTimeout:     90 * time.Second,
	DatabaseKillOpPeriod:  10 * time.Second,
	Auth:                  auth.None(),
	EnableCISearches:      true,
	CountTotalResults:     true,
	ReadOnly:              false,
	Debug:                 false,
}

DefaultConfig is the default server configuration

View Source
var ErrMultipleMatches = errors.New("Multiple Matches")

ErrMultipleMatches indicates that the conditional update query returned multiple matches

View Source
var ErrNotFound = errors.New("Resource Not Found")

ErrNotFound indicates an error

View Source
var ErrOpInterrupted = errors.New("Operation Interrupted")

ErrOpInterrupted indicates that the query was interrupted by a killOp() operation

Functions

func AbortNonJSONRequestsMiddleware

func AbortNonJSONRequestsMiddleware(c *gin.Context)

AbortNonJSONRequestsMiddleware is middleware that responds to any request that Accepts a Content-Type other than JSON (or a JSON flavor) with a 406 Not Acceptable status.

func FHIRBind

func FHIRBind(c *gin.Context, obj interface{}) error

func ReadOnlyMiddleware

func ReadOnlyMiddleware(c *gin.Context)

ReadOnlyMiddleware makes the API read-only and responds to any requests that are not GET, HEAD, or OPTIONS with a 405 Method Not Allowed error.

func RegisterController

func RegisterController(name string, e *gin.Engine, m []gin.HandlerFunc, dal DataAccessLayer, config Config)

RegisterController registers the CRUD routes (and middleware) for a FHIR resource

func RegisterRoutes

func RegisterRoutes(e *gin.Engine, config map[string][]gin.HandlerFunc, dal DataAccessLayer, serverConfig Config)

RegisterRoutes registers the routes for each of the FHIR resources

func RequestLoggerHandler

func RequestLoggerHandler(c *gin.Context)

RequestLoggerHandler is a handler intended to be used during debugging to log out the request details including the request headers and the request body. This should not be used in production as it has performance implications.

Types

type AfterRoutes

type AfterRoutes func(*gin.Engine)

type BatchController

type BatchController struct {
	DAL    DataAccessLayer
	Config Config
}

BatchController handles FHIR batch operations via input bundles

func NewBatchController

func NewBatchController(dal DataAccessLayer, config Config) *BatchController

NewBatchController creates a new BatchController based on the passed in DAL

func (*BatchController) Post

func (b *BatchController) Post(c *gin.Context)

Post processes and incoming batch request

type Config

type Config struct {
	// ServerURL is the full URL for the root of the server. This may be used
	// by other middleware to compute redirect URLs
	ServerURL string

	// Auth determines what, if any authentication and authorization will be used
	// by the FHIR server
	Auth auth.Config

	// IndexConfigPath is the path to an indexes.conf configuration file, specifying
	// what mongo indexes the server should create (or verify) on startup
	IndexConfigPath string

	// DatabaseHost is the url of the running mongo instance to use for the fhir database.
	DatabaseHost string

	// DatabaseName is the name of the mongo database used for the fhir database.
	// Typically this will be the default DatabaseName "fhir".
	DatabaseName string

	// DatabaseSocketTimeout is the amount of time the mgo driver will wait for a response
	// from mongo before timing out.
	DatabaseSocketTimeout time.Duration

	// DatabaseOpTimeout is the amount of time GoFHIR will wait before killing a long-running
	// database process. This defaults to a reasonable upper bound for slow, pipelined queries: 30s.
	DatabaseOpTimeout time.Duration

	// DatabaseKillOpPeriod is the length of time between scans of the database to kill long-running ops.
	DatabaseKillOpPeriod time.Duration

	// CountTotalResults toggles whether the searcher should also get a total
	// count of the total results of a search. In practice this is a performance hit
	// for large datasets.
	CountTotalResults bool

	// EnableCISearches toggles whether the mongo searches uses regexes to maintain
	// case-insesitivity when performing searches on string fields, codes, etc.
	EnableCISearches bool

	// ReadOnly toggles whether the server is in read-only mode. In read-only
	// mode any HTTP verb other than GET, HEAD or OPTIONS is rejected.
	ReadOnly bool

	// Debug toggles debug-level logging.
	Debug bool
}

Config is used to hold information about the configuration of the FHIR server.

type CurrentOp

type CurrentOp struct {
	Active           bool   `bson:"active" json:"active"`
	OpID             uint32 `bson:"opid" json:"opid"`
	SecsRunning      uint32 `bson:"secs_running" json:"secs_running"`
	MicrosecsRunning uint64 `bson:"microsecs_running" json:"microsecs_running"`
	OpType           string `bson:"op" json:"op"`
	Namespace        string `bson:"ns" json:"ns"`
	KillPending      bool   `bson:"killPending" json:"killPending"`
	Query            bson.D `bson:"query" json:"query"`
}

CurrentOp is a database operation currently in-progress.

type CurrentOps

type CurrentOps struct {
	InProg []CurrentOp `bson:"inprog" json:"inprog"`
	Info   string      `bson:"info,omitempty" json:"info,omitempty"`
	Ok     float64     `bson:"ok" json:"ok"`
}

CurrentOps is returned by db.currentOp() and contains a list of all operations currently in-progress. The db.currentOp() operation will itself be an element of InProg[].

type CustomJSONRenderer

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

CustomJSONRenderer replaces gin's default JSON renderer and ensures that the special characters "<", ">", and "&" are not escaped after the the JSON is marshaled. Escaping these special HTML characters is the default behavior of Go's json.Marshal(). It also ensures that the improperly unmarshaled "_id" field in contained resources gets converted correctly to "id".

func (CustomJSONRenderer) Render

func (u CustomJSONRenderer) Render(w http.ResponseWriter) (err error)

func (CustomJSONRenderer) WriteContentType

func (u CustomJSONRenderer) WriteContentType(w http.ResponseWriter)

type DataAccessLayer

type DataAccessLayer interface {
	// Get retrieves a single resource instance identified by its resource type and ID
	Get(id, resourceType string) (result interface{}, err error)
	// Post creates a resource instance, returning its new ID.
	Post(resource interface{}) (id string, err error)
	// PostWithID creates a resource instance with the given ID.
	PostWithID(id string, resource interface{}) error
	// Put creates or updates a resource instance with the given ID.
	Put(id string, resource interface{}) (createdNew bool, err error)
	// ConditionalPut creates or updates a resource based on search criteria.  If the criteria results in zero matches,
	// the resource is created.  If the criteria results in one match, it is updated.  Otherwise, a ErrMultipleMatches
	// error is returned.
	ConditionalPut(query search.Query, resource interface{}) (id string, createdNew bool, err error)
	// Delete removes the resource instance with the given ID.  This operation cannot be undone.
	Delete(id, resourceType string) error
	// ConditionalDelete removes zero or more resources matching the passed in search criteria.  This operation cannot
	// be undone.
	ConditionalDelete(query search.Query) (count int, err error)
	// Search executes a search given the baseURL and searchQuery.
	Search(baseURL url.URL, searchQuery search.Query) (result *models.Bundle, err error)
	// FindIDs executes a search given the searchQuery and returns only the matching IDs.  This function ignores
	// search options that don't make sense in this context: _include, _revinclude, _summary, _elements, _contained,
	// and _containedType.  It honors search options such as _count, _sort, and _offset.
	FindIDs(searchQuery search.Query) (result []string, err error)
}

DataAccessLayer is an interface for the various interactions that can occur on a FHIR data store.

func NewMongoDataAccessLayer

func NewMongoDataAccessLayer(ms *MasterSession, interceptors map[string]InterceptorList, config Config) DataAccessLayer

NewMongoDataAccessLayer returns an implementation of DataAccessLayer that is backed by a Mongo database

type FHIRServer

type FHIRServer struct {
	Config           Config
	Engine           *gin.Engine
	MiddlewareConfig map[string][]gin.HandlerFunc
	AfterRoutes      []AfterRoutes
	Interceptors     map[string]InterceptorList
}

func NewServer

func NewServer(config Config) *FHIRServer

func (*FHIRServer) AddInterceptor

func (f *FHIRServer) AddInterceptor(op, resourceType string, handler InterceptorHandler) error

AddInterceptor adds a new interceptor for a particular database operation and FHIR resource. For example: AddInterceptor("Create", "Patient", patientInterceptorHandler) would register the patientInterceptorHandler methods to be run against a Patient resource when it is created.

To run a handler against ALL resources pass "*" as the resourceType.

Supported database operations are: "Create", "Update", "Delete"

func (*FHIRServer) AddMiddleware

func (f *FHIRServer) AddMiddleware(key string, middleware gin.HandlerFunc)

func (*FHIRServer) Run

func (f *FHIRServer) Run()

type IndexMap

type IndexMap map[string][]*mgo.Index

IndexMap is a map of index arrays with the collection name as the key. Each index array contains one or more *mgo.Index indexes.

type Indexer

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

Indexer is the top-level interface for managing MongoDB indexes.

func NewIndexer

func NewIndexer(config Config) *Indexer

NewIndexer returns a pointer to a newly configured Indexer.

func (*Indexer) ConfigureIndexes

func (i *Indexer) ConfigureIndexes(ms *MasterSession)

ConfigureIndexes ensures that all indexes listed in the provided indexes.conf file are part of the Mongodb fhir database. If an index does not exist yet ConfigureIndexes creates a new index in the background using mgo.collection.EnsureIndex(). Depending on the size of the collection it may take some time before the index is created. This will block the current thread until the indexing completes, but will not block other connections to the mongo database.

type Interceptor

type Interceptor struct {
	ResourceType string
	Handler      InterceptorHandler
}

Interceptor optionally executes functions on a specified resource type before and after a database operation involving that resource. To register an interceptor for ALL resource types use a "*" as the resourceType.

type InterceptorHandler

type InterceptorHandler interface {
	Before(resource interface{})
	After(resource interface{})
	OnError(err error, resource interface{})
}

InterceptorHandler is an interface that defines three methods that are executed on a resource before the database operation, after the database operation SUCCEEDS, and after the database operation FAILS.

type InterceptorList

type InterceptorList []Interceptor

InterceptorList is a list of interceptors registered for a given database operation

type MasterSession

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

MasterSession manages a master session connected to the Mongo database. The user is responsible for creating and closing this master session. Each request to the database should first obtain a new WorkerSession, perform the desired operation(s), then close the WorkerSession.

func NewMasterSession

func NewMasterSession(session *mgo.Session, dbname string) (master *MasterSession)

NewMasterSession returns a new MasterSession object with an established session and database. Once instantiated the MasterSession object cannot be changed.

func (*MasterSession) GetWorkerSession

func (ms *MasterSession) GetWorkerSession() (worker *WorkerSession)

GetWorkerSession returns a new WorkerSession with a copy of the master mongo session.

type Reply

type Reply struct {
	Info string  `bson:"info,omitempty" json:"info,omitempty"`
	Ok   float64 `bson:"ok" json:"ok"`
}

Reply is a response from a MongoDB command that doesn't return any results.

type ResourceController

type ResourceController struct {
	Name   string
	DAL    DataAccessLayer
	Config Config
}

ResourceController provides the necessary CRUD handlers for a given resource.

func NewResourceController

func NewResourceController(name string, dal DataAccessLayer, config Config) *ResourceController

NewResourceController creates a new resource controller for the passed in resource name and the passed in DataAccessLayer.

func (*ResourceController) ConditionalDeleteHandler

func (rc *ResourceController) ConditionalDeleteHandler(c *gin.Context)

ConditionalDeleteHandler handles requests to delete resources identified by search criteria. All resources matching the search criteria will be deleted.

func (*ResourceController) ConditionalUpdateHandler

func (rc *ResourceController) ConditionalUpdateHandler(c *gin.Context)

ConditionalUpdateHandler handles requests for conditional updates. These requests contain search criteria for the resource to update. If the criteria results in no found resources, a new resource is created. If the criteria results in one found resource, that resource will be updated. Criteria resulting in more than one found resource is considered an error.

func (*ResourceController) CreateHandler

func (rc *ResourceController) CreateHandler(c *gin.Context)

CreateHandler handles requests to create a new resource instance, assigning it a new ID.

func (*ResourceController) DeleteHandler

func (rc *ResourceController) DeleteHandler(c *gin.Context)

DeleteHandler handles requests to delete a resource instance identified by its ID.

func (*ResourceController) EverythingHandler

func (rc *ResourceController) EverythingHandler(c *gin.Context)

EverythingHandler handles requests for everything related to a Patient or Encounter resource.

func (*ResourceController) IndexHandler

func (rc *ResourceController) IndexHandler(c *gin.Context)

IndexHandler handles requests to list resource instances or search for them.

func (*ResourceController) LoadResource

func (rc *ResourceController) LoadResource(c *gin.Context) (interface{}, error)

LoadResource uses the resource id in the request to get a resource from the DataAccessLayer and store it in the context.

func (*ResourceController) ShowHandler

func (rc *ResourceController) ShowHandler(c *gin.Context)

ShowHandler handles requests to get a particular resource by ID.

func (*ResourceController) UpdateHandler

func (rc *ResourceController) UpdateHandler(c *gin.Context)

UpdateHandler handles requests to update a resource having a given ID. If the resource with that ID does not exist, a new resource is created with that ID.

type ResourcePlusRelatedResources

type ResourcePlusRelatedResources interface {
	GetIncludedAndRevIncludedResources() map[string]interface{}
	GetIncludedResources() map[string]interface{}
	GetRevIncludedResources() map[string]interface{}
}

ResourcePlusRelatedResources is an interface to capture those structs that implement the functions for getting included and rev-included resources

type WorkerSession

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

WorkerSession is obtained from MasterSession.GetWorkerSession() and manages a temporary copy of the master session. A WorkerSession should be used for all requests to the database. When a WorkerSession is no longer needed it must be closed.

func (*WorkerSession) Close

func (ws *WorkerSession) Close()

Close closes the master session copy used by WorkerSession

func (*WorkerSession) DB

func (ws *WorkerSession) DB() (db *mgo.Database)

DB returns the mongo database available on the current session.

func (*WorkerSession) SetTimeout

func (ws *WorkerSession) SetTimeout(d time.Duration)

SetTimeout sets the session timeout for requests made using the worker's session. The default timeout is 1 minute.

Jump to

Keyboard shortcuts

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