Desired state is the task lifecycle state requested by a user or by an item placed on a worker’s queue. It describes where the task should be, not necessarily where it is now. section 5.4 section 7.6
Keep the two views of a task separate:
- The worker datastore records the actual state of tasks from the worker’s perspective. section 5.4
- The worker queue records requested state transitions for tasks to process. section 5.4
- The manager stores task events as user requests, selects a worker, and passes the requested task along. section 7.6
- A declarative manager tries to move the actual state toward the declared state; the initial implementation makes one attempt and does not retry failures. section 7.4
Stopping a task
A stop request creates a queue item whose state is task.Completed. The handler copies the task from the datastore, changes the copy’s state, and queues it. Mutating the datastore object directly would change the actual state before the worker processed the requested transition. section 5.4
Listing 5.4 The worker’s StartTaskHandler method
func (a *Api) StartTaskHandler(w http.ResponseWriter, r *http.Request) {
d := json.NewDecoder(r.Body) #1
d.DisallowUnknownFields() #2
te := task.TaskEvent{} #3
err := d.Decode(&te) #4
if err != nil { #5
msg := fmt.Sprintf("Error unmarshalling body: %v\n", err)
log.Printf(msg)
w.WriteHeader(400)
e := ErrResponse{
HTTPStatusCode: 400,
Message: msg,
}
json.NewEncoder(w).Encode(e)
return
}
a.Worker.AddTask(te.Task) #6
log.Printf("Added task %v\n", te.Task.ID) #7
w.WriteHeader(201) #8
json.NewEncoder(w).Encode(te.Task) #9
}
The handler listing shows how an API accepts a task event and adds its task to the worker, making the requested state operational. section 5.4
