github.com/ravendb/ravendb-go-client@v0.0.0-20240229102137-4474ee7aa0fa/operation.go (about) 1 package ravendb 2 3 import ( 4 "time" 5 ) 6 7 // Operation describes async operation being executed on the server 8 type Operation struct { 9 requestExecutor *RequestExecutor 10 //TBD private readonly Func<DatabaseChanges> _changes; 11 conventions *DocumentConventions 12 id int64 13 14 // if true, this represents ServerWideOperation 15 IsServerWide bool 16 } 17 18 func (o *Operation) GetID() int64 { 19 return o.id 20 } 21 22 func NewOperation(requestExecutor *RequestExecutor, changes func() *DatabaseChanges, conventions *DocumentConventions, id int64) *Operation { 23 return &Operation{ 24 requestExecutor: requestExecutor, 25 //TBD _changes = changes; 26 conventions: conventions, 27 id: id, 28 } 29 } 30 31 func (o *Operation) fetchOperationsStatus() (map[string]interface{}, error) { 32 command := o.getOperationStateCommand(o.conventions, o.id) 33 err := o.requestExecutor.ExecuteCommand(command, nil) 34 if err != nil { 35 return nil, err 36 } 37 38 switch cmd := command.(type) { 39 case *GetOperationStateCommand: 40 return cmd.Result, nil 41 case *GetServerWideOperationStateCommand: 42 return cmd.Result, nil 43 } 44 panicIf(true, "Unexpected command type %T", command) 45 return nil, nil 46 } 47 48 func (o *Operation) getOperationStateCommand(conventions *DocumentConventions, id int64) RavenCommand { 49 if o.IsServerWide { 50 return NewGetServerWideOperationStateCommand(o.conventions, id) 51 } 52 return NewGetOperationStateCommand(o.conventions, o.id) 53 } 54 55 func (o *Operation) WaitForCompletion() error { 56 for { 57 status, err := o.fetchOperationsStatus() 58 if err != nil { 59 return err 60 } 61 62 operationStatus, ok := jsonGetAsText(status, "Status") 63 if !ok { 64 return newRavenError("missing 'Status' field in response") 65 } 66 switch operationStatus { 67 case "Completed": 68 return nil 69 case "Cancelled": 70 return newOperationCancelledError("") 71 case "Faulted": 72 result, ok := status["Result"].(map[string]interface{}) 73 if !ok { 74 return newRavenError("status has no 'Result' object. Status: #%v", status) 75 } 76 var exceptionResult OperationExceptionResult 77 err = structFromJSONMap(result, &exceptionResult) 78 if err != nil { 79 return err 80 } 81 return exceptionDispatcherGet(exceptionResult.Message, exceptionResult.Error, exceptionResult.Type, exceptionResult.StatusCode, nil) 82 } 83 84 time.Sleep(500 * time.Millisecond) 85 } 86 }