Beispiel #1
0
func Parallel(handlers map[string]server.Handler) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			var status = make(map[string]int)
			var data = make(map[string]interface{})
			var mutex sync.Mutex
			var wg sync.WaitGroup
			for k, q := range handlers {
				wg.Add(1)
				go func(k string, h server.Handler) {
					defer wg.Done()
					v := h.Handle(req)
					if vv, ok := v.(*response.JSONResponse); ok {
						mutex.Lock()
						defer mutex.Unlock()
						status[k] = vv.StatusCode
						data[k] = vv.Data
					}
				}(k, q)
			}
			wg.Wait()
			for k, code := range status {
				// return non 2xx response
				if code > 0 && (code < 200 || code >= 300) {
					return response.NewJSONResponseWithStatus(data[k], code)
				}
			}
			return response.NewJSONResponse(data)
		})
}
Beispiel #2
0
func EntityPost(post *entities.Put) server.Handler {
	return server.Handler(
		func(req *wcg.Request) response.Response {
			ent, err := post.Kind().CreateEntityFromForm(req.HTTPRequest().Form)
			if err != nil { // ParseError
				req.Logger.Warnf("You should use ParseForm middleware to avoid the error in EntityPost: %v", err)
				return response.BadRequest(req, ErrInvalidFormParameters)
			}
			_, ent_ := post.MustUpdate(req, ent)
			return response.NewJSONResponseWithStatus(ent_, 201)
		})
}
Beispiel #3
0
// Process implements wcg.Handler#Process
func (h *Cron) Process(res *wcg.Response, req *wcg.Request) {
	req.Logger.Infof("[Cron] %s (%s) - start", h.Path, h.Time)
	for _, handler := range h.handlers {
		if err := handler(req); err != nil {
			req.Logger.Fatalf("[Cron] %s (%s) - error: %v", h.Path, h.Description, err)
			response.NewJSONResponseWithStatus(err, 500).Render(res, req)
			return
		}
	}
	req.Logger.Infof("[Cron] %s (%s) - finish", h.Path, h.Description)
	response.NewJSONResponse(true).Render(res, req)
	return
}
Beispiel #4
0
func processEntityPut(req *wcg.Request, put *entities.Put, keyParams string, create bool) response.Response {
	key := req.Param(keyParams)
	_, ent := put.Kind().Get().Key(key).UseDefaultIfNil(create).MustOne(req)
	if ent == nil {
		return response.APINotFound
	}
	if req.HTTPRequest().Form == nil {
		req.Logger.Warnf("You should use ParseForm middleware to avoid the error in EntityPut|EntityPutOrCreate")
		return response.InternalServerError(req, ErrInvalidFormParameters).(response.Response)
	}
	err := put.Kind().UpdateEntityFromForm(ent, req.HTTPRequest().Form)
	if err != nil {
		return response.BadRequest(req, ErrInvalidFormParameters)
	}
	_, ent_ := put.Key(key).MustUpdate(req, ent)
	return response.NewJSONResponseWithStatus(ent_, 200)
}
Beispiel #5
0
// Define endpoints to process an async task.
func (helper *AsyncAPIHelper) Define(path string) *AsyncAPIConfig {
	if !strings.HasSuffix(path, "/") {
		panic(fmt.Errorf("Task endpoint must end with '/' (%s)", path))
	}
	api := helper.app.API()
	// /path/to/something/ => api-path-to-something
	p := api.Path(path)
	name := strings.Replace(p[1:len(p)-1], ":", "", -1) // remove parameters
	name = strings.Replace(name, "/", "-", -1)          // replace '/' with '-'
	config := &AsyncAPIConfig{
		Queue: helper.app.Queue().DefinePush(name),
		app:   helper.app,
		path:  path,
	}

	// Endpoint that trigger the task.
	api.POST(path, Handler(
		func(req *wcg.Request) response.Response {
			for _, h := range config.triggerHandlers {
				resp := h.Handle(req)
				if resp != nil {
					req.Logger.Debugf("Async Task is not triggered.")
					return resp
				}
			}
			task := &models.AsyncAPITask{}
			task.ID = wcg.NewUUID()
			task.Path = path
			task.Query = req.HTTPRequest().URL.RawQuery
			task.Status = models.AsyncAPIStatusReady
			entities.AsyncAPITask.Put().Key(string(task.ID)).MustUpdate(req, task)
			// Push a task
			taskPath := fmt.Sprintf("%s%s.json?%s", req.URL().Path, string(task.ID), req.HTTPRequest().URL.Query().Encode())
			if err := config.Queue.PushTask(req, taskPath, nil); err != nil {
				return response.InternalServerError(req, err)
			}
			req.Logger.Infof("Triggered an async task [id:%s path:%s]", task.ID, taskPath)
			return response.NewJSONResponseWithStatus(
				AsyncTaskTriggerResponse{task.ID},
				201,
			)
		},
	))

	// Endpoint that executes the task in background
	// This endpoint must be called by PushQueue
	api.POST(path+":taskid.json", Handler(
		func(req *wcg.Request) response.Response {
			if !request.IsTask(req) {
				req.Logger.Warnf(
					"Non system call to the async task endpoint: UserAgent=%s, IP=%s",
					req.HTTPRequest().UserAgent(),
					req.HTTPRequest().RemoteAddr,
				)
				return response.APIOK
			}

			_, one := entities.AsyncAPITask.Get().Key(req.Param("taskid")).MustOne(req)
			if one == nil {
				req.Logger.Warnf(
					"Task %q not found: UserAgent=%s, IP=%s",
					req.Param("taskid"),
					req.HTTPRequest().UserAgent(),
					req.HTTPRequest().RemoteAddr,
				)
				return response.APIOK
			}
			task := one.(*models.AsyncAPITask)
			logger := wcg.NewLoggerWithPrefix(req, fmt.Sprintf("[AsyncTask: %s (queue: %s)]", task.ID, name))
			if task.Status != models.AsyncAPIStatusReady && task.Status != models.AsyncAPIStatusRunning {
				logger.Warnf("Task is not ready: Status=%s", task.Status)
				return response.APIOK
			}

			if task.Status == models.AsyncAPIStatusReady {
				task.StartAt = lib.Now()
				task.Status = models.AsyncAPIStatusRunning
				entities.AsyncAPITask.Put().Key(req.Param("taskid")).MustUpdate(req, task)
			}

			var err error
			var progress *models.AsyncAPITaskProgress
			var resp response.Response
			func() {
				defer func() {
					if x := recover(); x != nil {
						logger.Errorf("Unhandle error recovered from the task: %v", x)
						err = fmt.Errorf("%v", x)
					}
				}()
				progress, err = config.processHandler(req, task)
			}()

			if progress != nil {
				task.Progress = append(task.Progress, *progress)
			}
			if progress != nil && progress.Next != nil {
				// update the entity (Progress field)
				entities.AsyncAPITask.Put().Key(req.Param("taskid")).MustUpdate(req, task)

				// Push a next request into the queue
				// This is not required in test environment as test code manually call the next request (see testhelper.AsyncTaskTestRunner#Run code)
				// The test environment uses the response JSON to call the next URL and that response is used only for this purpose.
				// If the code cannot push task for the next request, we should stop the task as failure.
				logger.Infof("Task needs to call recursively: Next parameter is %v", progress.Next)
				if !req.IsTest() {
					err = config.Queue.PushTask(req, fmt.Sprintf("%s?%s", req.URL().Path, progress.Next.Encode()), nil)
				}
				if err == nil {
					return response.NewJSONResponse(progress.Next)
				}
				// if an error occurrs by PushTask, just stopping the task and update the datastore as failure.
			}
			// finished the task
			task.FinishAt = lib.Now()
			tt := task.FinishAt.Sub(task.StartAt)
			if err == nil {
				task.Status = models.AsyncAPIStatusSuccess
				logger.Infof("Task finished successfully (time: %s)", tt.String())
				resp = response.APIOK
			} else {
				task.Error = err.Error()
				task.Status = models.AsyncAPIStatusFailure
				logger.Errorf("Task failed (time: %s): %s", tt.String(), task.Error)
				resp = response.APIInternalServerError
			}
			entities.AsyncAPITask.Put().Key(req.Param("taskid")).MustUpdate(req, task)
			return resp
		},
	))

	// Endpoint that returns the task status.
	api.GET(path+":taskid.json", Handler(
		func(req *wcg.Request) response.Response {
			for _, h := range config.triggerHandlers {
				resp := h.Handle(req)
				if resp != nil {
					return resp
				}
			}
			_, one := entities.AsyncAPITask.Get().Key(req.Param("taskid")).MustOne(req)
			if one == nil {
				return response.NotFound(req)
			}
			task := one.(*models.AsyncAPITask)
			return response.NewJSONResponse(
				AsyncTaskMonitorResponse{
					ID:       task.ID,
					Status:   task.Status,
					Progress: task.LastProgress(),
				},
			)
		},
	))

	return config
}