/
requests.go
716 lines (597 loc) · 22.4 KB
/
requests.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
package api
import (
"context"
"database/sql"
"encoding/json"
goerrors "errors"
"fmt"
"os"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"github.com/pkg/errors"
"net/http"
"time"
"github.com/pborman/uuid"
"github.com/CMSgov/bcda-app/bcda/auth"
"github.com/CMSgov/bcda-app/bcda/client"
"github.com/CMSgov/bcda-app/bcda/constants"
"github.com/CMSgov/bcda-app/bcda/database"
"github.com/CMSgov/bcda-app/bcda/models"
"github.com/CMSgov/bcda-app/bcda/models/postgres"
responseutils "github.com/CMSgov/bcda-app/bcda/responseutils"
responseutilsv2 "github.com/CMSgov/bcda-app/bcda/responseutils/v2"
"github.com/CMSgov/bcda-app/bcda/service"
"github.com/CMSgov/bcda-app/bcda/servicemux"
"github.com/CMSgov/bcda-app/bcda/utils"
"github.com/CMSgov/bcda-app/bcda/web/middleware"
"github.com/CMSgov/bcda-app/bcdaworker/queueing"
"github.com/CMSgov/bcda-app/conf"
"github.com/CMSgov/bcda-app/log"
)
type Handler struct {
JobTimeout time.Duration
Enq queueing.Enqueuer
Svc service.Service
// Needed to have access to the repository/db for lookup needed in the bulkRequest.
// TODO (BCDA-3412): Remove this reference once we've captured all of the necessary
// logic into a service method.
r models.Repository
db *sql.DB
supportedDataTypes map[string]service.DataType
supportedResourceTypes []string
supportedStatuses map[models.JobStatus]struct{}
bbBasePath string
apiVersion string
RespWriter fhirResponseWriter
}
type fhirResponseWriter interface {
Exception(context.Context, http.ResponseWriter, int, string, string)
NotFound(context.Context, http.ResponseWriter, int, string, string)
JobsBundle(context.Context, http.ResponseWriter, []*models.Job, string)
}
func NewHandler(dataTypes map[string]service.DataType, basePath string, apiVersion string) *Handler {
return newHandler(dataTypes, basePath, apiVersion, database.Connection)
}
func newHandler(dataTypes map[string]service.DataType, basePath string, apiVersion string, db *sql.DB) *Handler {
h := &Handler{JobTimeout: time.Hour * time.Duration(utils.GetEnvInt("ARCHIVE_THRESHOLD_HR", 24))}
h.Enq = queueing.NewEnqueuer()
cfg, err := service.LoadConfig()
if err != nil {
log.API.Fatalf("Failed to load service config. Err: %v", err)
}
repository := postgres.NewRepository(db)
h.db, h.r = db, repository
h.Svc = service.NewService(repository, cfg, basePath)
h.supportedDataTypes = dataTypes
// Build string array of supported Resource types
h.supportedResourceTypes = make([]string, 0, len(h.supportedDataTypes))
for k := range h.supportedDataTypes {
h.supportedResourceTypes = append(h.supportedResourceTypes, k)
}
h.supportedStatuses = make(map[models.JobStatus]struct{}, len(models.AllJobStatuses))
for _, r := range models.AllJobStatuses {
h.supportedStatuses[r] = struct{}{}
}
h.bbBasePath = basePath
h.apiVersion = apiVersion
switch h.apiVersion {
case "v1":
h.RespWriter = responseutils.NewResponseWriter()
case "v2":
h.RespWriter = responseutilsv2.NewResponseWriter()
default:
log.API.Fatalf("unexpected API version: %s", h.apiVersion)
}
return h
}
func (h *Handler) BulkPatientRequest(w http.ResponseWriter, r *http.Request) {
reqType := service.DefaultRequest // historical data for new beneficiaries will not be retrieved (this capability is only available with /Group)
h.bulkRequest(w, r, reqType)
}
func (h *Handler) ALRRequest(w http.ResponseWriter, r *http.Request) {
h.alrRequest(w, r)
}
func (h *Handler) BulkGroupRequest(w http.ResponseWriter, r *http.Request) {
const (
groupAll = "all"
groupRunout = "runout"
)
reqType := service.DefaultRequest
groupID := chi.URLParam(r, "groupId")
switch groupID {
case groupAll:
// Set flag to retrieve new beneficiaries' historical data if _since param is provided and feature is turned on
_, ok := r.URL.Query()["_since"]
if ok && utils.GetEnvBool("BCDA_ENABLE_NEW_GROUP", false) {
reqType = service.RetrieveNewBeneHistData
}
case groupRunout:
if utils.GetEnvBool("BCDA_ENABLE_RUNOUT", true) {
reqType = service.Runout
break
}
fallthrough
default:
h.RespWriter.Exception(r.Context(), w, http.StatusBadRequest, responseutils.RequestErr, "Invalid group ID")
return
}
h.bulkRequest(w, r, reqType)
}
func (h *Handler) JobsStatus(w http.ResponseWriter, r *http.Request) {
var (
ad auth.AuthData
statusTypes []models.JobStatus
err error
)
logger := log.GetCtxLogger(r.Context())
statusTypes = models.AllJobStatuses // default request to retrieve jobs with all statuses
params, ok := r.URL.Query()["_status"]
if ok {
statusMap := make(map[string]struct{})
rawStatusTypes := strings.Split(params[0], ",")
statusTypes = nil
// validate no duplicate status types
for _, status := range rawStatusTypes {
if _, ok := statusMap[status]; !ok {
statusMap[status] = struct{}{}
statusTypes = append(statusTypes, models.JobStatus(status))
} else {
errMsg := fmt.Sprintf("Repeated status type %s", status)
h.RespWriter.Exception(r.Context(), w, http.StatusBadRequest, responseutils.RequestErr, errMsg)
return
}
}
// validate status types provided match our valid list of statuses
if err = h.validateStatuses(statusTypes); err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusBadRequest, responseutils.RequestErr, err.Error())
return
}
}
if ad, err = readAuthData(r); err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusUnauthorized, responseutils.TokenErr, "")
return
}
jobs, err := h.Svc.GetJobs(r.Context(), uuid.Parse(ad.ACOID), statusTypes...)
if err != nil {
logger.Error(err)
if ok := goerrors.As(err, &service.JobsNotFoundError{}); ok {
h.RespWriter.Exception(r.Context(), w, http.StatusNotFound, responseutils.DbErr, err.Error())
} else {
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "")
}
}
scheme := "http"
if servicemux.IsHTTPS(r) {
scheme = "https"
}
host := fmt.Sprintf("%s://%s", scheme, r.Host)
// pass in the ctx here and log with the ctx logger
h.RespWriter.JobsBundle(r.Context(), w, jobs, host)
}
func (h *Handler) validateStatuses(statusTypes []models.JobStatus) error {
for _, statusType := range statusTypes {
if _, ok := h.supportedStatuses[statusType]; !ok {
return fmt.Errorf("invalid status type %s. Supported types %s", statusType, h.supportedStatuses)
}
}
return nil
}
func (h *Handler) JobStatus(w http.ResponseWriter, r *http.Request) {
logger := log.GetCtxLogger(r.Context())
jobIDStr := chi.URLParam(r, "jobID")
jobID, err := strconv.ParseUint(jobIDStr, 10, 64)
if err != nil {
err = errors.Wrap(err, "cannot convert jobID to uint")
logger.Error(err)
//We don't need to return the full error to a consumer.
//We pass a bad request header (400) for this exception due to the inputs always being invalid for our purposes
h.RespWriter.Exception(r.Context(), w, http.StatusBadRequest, responseutils.RequestErr, "could not parse job id")
return
}
job, jobKeys, err := h.Svc.GetJobAndKeys(r.Context(), uint(jobID))
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
log.API.Info("Requested job not found.", err.Error())
h.RespWriter.Exception(r.Context(), w, http.StatusNotFound, responseutils.DbErr, "Job not found.")
} else {
log.API.Error("Error attempting to request job. Error:", err.Error())
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "Error trying to fetch job. Please try again.")
}
return
}
switch job.Status {
case models.JobStatusFailed, models.JobStatusFailedExpired:
logger.Error(job.Status)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.JobFailed, responseutils.DetailJobFailed)
case models.JobStatusPending, models.JobStatusInProgress:
w.Header().Set("X-Progress", job.StatusMessage())
w.WriteHeader(http.StatusAccepted)
return
case models.JobStatusCompleted:
// If the job should be expired, but the cleanup job hasn't run for some reason, still respond with 410
if job.UpdatedAt.Add(h.JobTimeout).Before(time.Now()) {
w.Header().Set("Expires", job.UpdatedAt.Add(h.JobTimeout).String())
h.RespWriter.Exception(r.Context(), w, http.StatusGone, responseutils.NotFoundErr, "")
return
}
w.Header().Set("Content-Type", constants.JsonContentType)
w.Header().Set("Expires", job.UpdatedAt.Add(h.JobTimeout).String())
scheme := "http"
if servicemux.IsHTTPS(r) {
scheme = "https"
}
rb := BulkResponseBody{
TransactionTime: job.TransactionTime,
RequestURL: job.RequestURL,
RequiresAccessToken: true,
Files: []FileItem{},
Errors: []FileItem{},
JobID: job.ID,
}
for _, jobKey := range jobKeys {
// data files
fi := FileItem{
Type: jobKey.ResourceType,
URL: fmt.Sprintf("%s://%s/data/%d/%s", scheme, r.Host, jobID, strings.TrimSpace(jobKey.FileName)),
}
// Check if "error" is not in the filename
if !strings.Contains(strings.ToLower(jobKey.FileName), "-error.ndjson") {
rb.Files = append(rb.Files, fi)
}
// Error files
errFileName := strings.Split(jobKey.FileName, ".")[0]
errFilePath := fmt.Sprintf("%s/%d/%s-error.ndjson", conf.GetEnv("FHIR_PAYLOAD_DIR"), jobID, errFileName)
// Check if the error file exists
if _, err := os.Stat(errFilePath); !os.IsNotExist(err) {
errFI := FileItem{
Type: "OperationOutcome",
URL: fmt.Sprintf("%s://%s/data/%d/%s-error.ndjson", scheme, r.Host, jobID, errFileName),
}
rb.Errors = append(rb.Errors, errFI)
}
}
jsonData, err := json.Marshal(rb)
if err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "")
return
}
_, err = w.Write([]byte(jsonData))
if err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "")
return
}
w.WriteHeader(http.StatusOK)
case models.JobStatusArchived, models.JobStatusExpired:
w.Header().Set("Expires", job.UpdatedAt.Add(h.JobTimeout).String())
h.RespWriter.Exception(r.Context(), w, http.StatusGone, responseutils.NotFoundErr, "")
case models.JobStatusCancelled, models.JobStatusCancelledExpired:
h.RespWriter.NotFound(r.Context(), w, http.StatusNotFound, responseutils.NotFoundErr, "Job has been cancelled.")
}
}
func (h *Handler) DeleteJob(w http.ResponseWriter, r *http.Request) {
logger := log.GetCtxLogger(r.Context())
jobIDStr := chi.URLParam(r, "jobID")
jobID, err := strconv.ParseUint(jobIDStr, 10, 64)
if err != nil {
err = errors.Wrap(err, "cannot convert jobID to uint")
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusBadRequest, responseutils.RequestErr, err.Error())
return
}
_, err = h.Svc.CancelJob(r.Context(), uint(jobID))
if err != nil {
switch err {
case service.ErrJobNotCancellable:
logger.Info(errors.Wrap(err, "Job is not cancellable"))
h.RespWriter.Exception(r.Context(), w, http.StatusGone, responseutils.DeletedErr, err.Error())
return
default:
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.DbErr, err.Error())
return
}
}
w.WriteHeader(http.StatusAccepted)
}
type AttributionFileStatus struct {
Timestamp time.Time `json:"timestamp"`
Type string `json:"type"`
}
type AttributionFileStatusResponse struct {
Data []AttributionFileStatus `json:"ingestion_dates"`
}
func (h *Handler) AttributionStatus(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := log.GetCtxLogger(ctx)
var (
ad auth.AuthData
err error
resp AttributionFileStatusResponse
)
if ad, err = readAuthData(r); err != nil {
logger.Error(err)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// Retrieve the most recent cclf 8 file we have successfully ingested
asd, err := h.getAttributionFileStatus(ctx, ad.CMSID, models.FileTypeDefault)
if err != nil {
logger.Error(errors.Wrap(err, "Failed to retrieve recent CCLF8 file"))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if asd != nil {
resp.Data = append(resp.Data, *asd)
}
// Retrieve the most recent cclf 8 runout file we have successfully ingested
asr, err := h.getAttributionFileStatus(ctx, ad.CMSID, models.FileTypeRunout)
if err != nil {
logger.Error(errors.Wrap(err, "Failed to retrieve recent runout CCLF8 file"))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if asr != nil {
resp.Data = append(resp.Data, *asr)
}
if resp.Data == nil {
logger.Error(errors.New("Could not find any CCLF8 files"))
h.RespWriter.Exception(r.Context(), w, http.StatusNotFound, responseutils.NotFoundErr, "")
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(resp)
if err != nil {
logger.Error(errors.Wrap(err, "Failed to encode JSON response"))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
w.WriteHeader(http.StatusOK)
}
func (h *Handler) getAttributionFileStatus(ctx context.Context, CMSID string, fileType models.CCLFFileType) (*AttributionFileStatus, error) {
logger := log.GetCtxLogger(ctx)
cclfFile, err := h.Svc.GetLatestCCLFFile(ctx, CMSID, fileType)
if err != nil {
logger.Error(err)
if ok := goerrors.As(err, &service.CCLFNotFoundError{}); ok {
return nil, nil
} else {
return nil, err
}
}
status := &AttributionFileStatus{
Timestamp: cclfFile.Timestamp,
}
switch fileType {
case models.FileTypeDefault:
status.Type = "last_attribution_update"
case models.FileTypeRunout:
status.Type = "last_runout_update"
}
return status, nil
}
func (h *Handler) bulkRequest(w http.ResponseWriter, r *http.Request, reqType service.RequestType) {
// Create context to encapsulate the entire workflow. In the future, we can define child context's for timing.
ctx := r.Context()
logger := log.GetCtxLogger(ctx)
var (
ad auth.AuthData
err error
)
if ad, err = readAuthData(r); err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusUnauthorized, responseutils.TokenErr, "")
return
}
rp, ok := middleware.RequestParametersFromContext(ctx)
if !ok {
panic("Request parameters must be set prior to calling this handler.")
}
resourceTypes := h.getResourceTypes(rp, ad.CMSID)
if err = h.validateResources(resourceTypes, ad.CMSID); err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusBadRequest, responseutils.RequestErr, err.Error())
return
}
bb, err := client.NewBlueButtonClient(client.NewConfig(h.bbBasePath))
if err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "")
return
}
acoID := uuid.Parse(ad.ACOID)
scheme := "http"
if servicemux.IsHTTPS(r) {
scheme = "https"
}
newJob := models.Job{
ACOID: acoID,
RequestURL: fmt.Sprintf("%s://%s%s", scheme, r.Host, r.URL),
Status: models.JobStatusPending,
}
// Need to create job in transaction instead of the very end of the process because we need
// the newJob.ID field to be set in the associated queuejobs. By doing the job creation (and update)
// in a transaction, we can rollback if we encounter any errors with handling the data needed for the newJob
tx, err := h.db.BeginTx(ctx, nil)
if err != nil {
err = fmt.Errorf("failed to start transaction: %w", err)
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "")
return
}
// Use a transaction backed repository to ensure all of our upserts are encapsulated into a single transaction
rtx := postgres.NewRepositoryTx(tx)
defer func() {
if err != nil {
if err1 := tx.Rollback(); err1 != nil {
logger.Warnf("Failed to rollback transaction %s", err.Error())
}
// We've already written out the HTTP response so we can return after we've rolled back the transaction
return
}
// We create the job after populating all of the data needed for the job (including inserting all of the queue jobs) to
// ensure that the job will be able to be processed and it WILL NOT BE stuck in the Pending state.
// For example, we write that the job has 10 queuejobs. We fail after inserting 9 queuejobs. The job will
// never move out of the IN_PROGRESS (or PENDING) state since we'll never be able to add the last queuejob.
//
// Since the queue jobs may (and do) exist in a different database, we cannot use a single transaction to encompass
// both adding queuejobs and adding the parent job.
//
// This does introduce an error scenario where we have queuejobs but no parent job.
// We've added logic into the worker to handle this situation.
if err = tx.Commit(); err != nil {
logger.Error(err.Error())
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.DbErr, "")
return
}
// We've successfully created the job
w.Header().Set("Content-Location", fmt.Sprintf("%s://%s/api/%s/jobs/%d", scheme, r.Host, h.apiVersion, newJob.ID))
w.WriteHeader(http.StatusAccepted)
}()
newJob.ID, err = rtx.CreateJob(ctx, newJob)
if err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.DbErr, "")
return
}
if newJob.ID != 0 {
ctx, logger = log.SetCtxLogger(ctx, "job_id", newJob.ID)
logger.Info("job id created")
}
jobData := models.JobEnqueueArgs{
ID: int(newJob.ID),
ACOID: acoID.String(),
Since: "",
TransactionTime: time.Now(),
CMSID: ad.CMSID,
}
// request a fake patient in order to acquire the bundle's lastUpdated metadata
b, err := bb.GetPatient(jobData, "0")
if err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.FormatErr, "Failure to retrieve transactionTime metadata from FHIR Data Server.")
return
}
newJob.TransactionTime = b.Meta.LastUpdated
var queJobs []*models.JobEnqueueArgs
conditions := service.RequestConditions{
ReqType: reqType,
Resources: resourceTypes,
CMSID: ad.CMSID,
ACOID: newJob.ACOID,
JobID: newJob.ID,
Since: rp.Since,
TransactionTime: newJob.TransactionTime,
CreationTime: time.Now(),
}
queJobs, err = h.Svc.GetQueJobs(ctx, conditions)
if err != nil {
logger.Error(err)
var (
respCode int
errType string
)
if ok := goerrors.As(err, &service.CCLFNotFoundError{}); ok && reqType == service.Runout {
respCode = http.StatusNotFound
errType = responseutils.NotFoundErr
} else {
respCode = http.StatusInternalServerError
errType = responseutils.InternalErr
}
h.RespWriter.Exception(r.Context(), w, respCode, errType, err.Error())
return
}
newJob.JobCount = len(queJobs)
// We've now computed all of the fields necessary to populate a fully defined job
if err = rtx.UpdateJob(ctx, newJob); err != nil {
logger.Error(err.Error())
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.DbErr, "")
return
}
// Since we're enqueuing these queuejobs BEFORE we've created the actual job, we may encounter a transient
// error where the job does not exist. Since queuejobs are retried, the transient error will be resolved
// once we finish inserting the job.
for _, j := range queJobs {
sinceParam := (!rp.Since.IsZero() || conditions.ReqType == service.RetrieveNewBeneHistData)
jobPriority := h.Svc.GetJobPriority(conditions.CMSID, j.ResourceType, sinceParam) // first argument is the CMS ID, not the ACO uuid
if err = h.Enq.AddJob(*j, int(jobPriority)); err != nil {
logger.Error(err)
h.RespWriter.Exception(r.Context(), w, http.StatusInternalServerError, responseutils.InternalErr, "")
return
}
}
}
func (h *Handler) getResourceTypes(parameters middleware.RequestParameters, cmsID string) []string {
resourceTypes := parameters.ResourceTypes
// If caller does not supply resource types, we default to all supported resource types for the specific ACO
if len(resourceTypes) == 0 {
if acoConfig, found := h.Svc.GetACOConfigForID(cmsID); found {
if utils.ContainsString(acoConfig.Data, constants.Adjudicated) {
resourceTypes = append(resourceTypes, "Patient", "ExplanationOfBenefit", "Coverage")
}
if utils.ContainsString(acoConfig.Data, constants.PartiallyAdjudicated) && h.apiVersion != "v1" {
resourceTypes = append(resourceTypes, "Claim", "ClaimResponse")
}
}
}
return resourceTypes
}
func (h *Handler) validateResources(resourceTypes []string, cmsID string) error {
for _, resourceType := range resourceTypes {
dataType, ok := h.supportedDataTypes[resourceType]
if !ok {
return fmt.Errorf("invalid resource type %s. Supported types %s", resourceType, h.supportedResourceTypes)
}
if !h.authorizedResourceAccess(dataType, cmsID) {
return fmt.Errorf("unauthorized resource type %s", resourceType)
}
}
return nil
}
func (h *Handler) authorizedResourceAccess(dataType service.DataType, cmsID string) bool {
if cfg, ok := h.Svc.GetACOConfigForID(cmsID); ok {
return (dataType.Adjudicated && utils.ContainsString(cfg.Data, constants.Adjudicated)) ||
(dataType.PartiallyAdjudicated && utils.ContainsString(cfg.Data, constants.PartiallyAdjudicated))
}
return false
}
func readAuthData(r *http.Request) (data auth.AuthData, err error) {
var ok bool
data, ok = r.Context().Value(auth.AuthDataContextKey).(auth.AuthData)
if !ok {
err = goerrors.New("no auth data in context")
}
return
}
// swagger:model fileItem
type FileItem struct {
// FHIR resource type of file contents
Type string `json:"type"`
// URL of the file
URL string `json:"url"`
}
/*
Data export job has completed successfully. The response body will contain a JSON object providing metadata about the transaction.
swagger:response completedJobResponse
*/
// nolint
type CompletedJobResponse struct {
// in: body
Body BulkResponseBody
}
type BulkResponseBody struct {
// Server time when the query was run
TransactionTime time.Time `json:"transactionTime"`
// URL of the bulk data export request
RequestURL string `json:"request"`
// Indicates whether an access token is required to download generated data files
RequiresAccessToken bool `json:"requiresAccessToken"`
// Information about generated data files, including URLs for downloading
Files []FileItem `json:"output"`
// Information about error files, including URLs for downloading
Errors []FileItem `json:"error"`
JobID uint
}