Finally finished
This commit is contained in:
parent
309b836931
commit
5b213eb72f
10 changed files with 112 additions and 60 deletions
|
@ -12,7 +12,8 @@ import (
|
|||
)
|
||||
|
||||
/* Stores a map between job ID and a string pointer. Nil for job not done yet */
|
||||
var waitingJobs map[string]*string = make (map[string]*string);
|
||||
var waitingJobs map[string]*string = make(map[string]*string);
|
||||
/* Mutex for waitingJobs list */
|
||||
var waitingJobsMutex sync.RWMutex;
|
||||
|
||||
/* Method which module http calls to forward the request to the subprocess*/
|
||||
|
@ -23,6 +24,7 @@ func Request(body map[string]any) (responseJSON string, err error) {
|
|||
}
|
||||
|
||||
// Generate ID and store it
|
||||
// 32 chars of base 64 is secure enough to assume no accidental collision
|
||||
var id string = genID();
|
||||
if len(id) == 0 {
|
||||
err = errors.New("Error generating ID!");
|
||||
|
@ -42,35 +44,55 @@ func Request(body map[string]any) (responseJSON string, err error) {
|
|||
waitingJobs[id] = nil;
|
||||
waitingJobsMutex.Unlock();
|
||||
|
||||
// Timeout waiting for response after 30 seconds
|
||||
timeoutTime := time.Now().Add(time.Second * 30);
|
||||
|
||||
// Wait for request to return
|
||||
for {
|
||||
// Check every milisecond
|
||||
time.Sleep(time.Millisecond)
|
||||
|
||||
// check if job is fufiled
|
||||
waitingJobsMutex.RLock();
|
||||
if waitingJobs[id] != nil {
|
||||
waitingJobsMutex.RUnlock();
|
||||
break;
|
||||
}
|
||||
waitingJobsMutex.RUnlock();
|
||||
|
||||
// If request takes more than 30 seconds
|
||||
/* This is technically a race condition, as the job could be fufiled
|
||||
between here and the job fufiled check, but it's the difference of
|
||||
a milisecond or two out of 30 seconds */
|
||||
if time.Now().After(timeoutTime) {
|
||||
// Delete job from queue
|
||||
waitingJobsMutex.Lock();
|
||||
delete(waitingJobs, id)
|
||||
waitingJobsMutex.Unlock();
|
||||
return "", errors.New("Request timed out!");
|
||||
}
|
||||
}
|
||||
|
||||
// Lock job when dequeueing
|
||||
waitingJobsMutex.Lock();
|
||||
responseJSON = *waitingJobs[id];
|
||||
delete(waitingJobs, id)
|
||||
delete(waitingJobs, id) // Remove job from "queue"
|
||||
waitingJobsMutex.Unlock();
|
||||
|
||||
err = nil;
|
||||
err = nil; // No problems
|
||||
return;
|
||||
}
|
||||
|
||||
/* Handles putting a response into waitingJobs. Returns false on error */
|
||||
func handleResponse(body string, unmarshaledJSONMap map[string]any) {
|
||||
waitingJobsMutex.RLock(); // Read lock
|
||||
val, ok := unmarshaledJSONMap["id"];
|
||||
waitingJobsMutex.RUnlock();
|
||||
if !ok {return}
|
||||
id, ok := val.(string)
|
||||
if !ok {return}
|
||||
|
||||
// Read-Write lock the mutex
|
||||
// Read-Write lock the mutex when writing job result
|
||||
waitingJobsMutex.Lock();
|
||||
defer waitingJobsMutex.Unlock();
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue