Finally functional

This commit is contained in:
Ben 2025-07-28 22:35:06 -07:00
parent be8936a665
commit b673c640e4
Signed by: webmaster
GPG key ID: A5FCBAF34E6E8B50
12 changed files with 261 additions and 113 deletions

View file

@ -2,20 +2,82 @@ package subprocess
/* This file manages verifying/sanatizing the request and response and forwarding it to the subprocess */
/* Method which module http calls to create the subprocess */
func Run(path string, body []byte) (status int, bodyContents []byte, err error) {
arguments := getArguments(path, body);
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"sync"
"time"
)
/* 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 waitingJobsMutex sync.RWMutex;
/* Method which module http calls to forward the request to the subprocess*/
func Request(body map[string]any) (responseJSON string, err error) {
if _, ok := body["id"]; ok {
err = errors.New("Request cannot contain id!");
return
}
// Don't know what to do with this request
if arguments == nil {return 404, []byte("Unknown request\n"), nil;}
// Generate ID and store it
var id string = genID();
if len(id) == 0 {
err = errors.New("Error generating ID!");
return
}
body["id"] = id;
// Call subprocess
status, bodyContents, err = runCommand(arguments);
// Marshal JSON to bytes
contents, err := json.Marshal(body)
if err != nil {return "", err}
return
// Lock job when enqueueing
waitingJobsMutex.Lock();
writeCMD(string(contents));
waitingJobs[id] = nil;
waitingJobsMutex.Unlock();
// Wait for request to finish
for waitingJobs[id] == nil {
time.Sleep(time.Millisecond)
}
// Lock job when dequeueing
waitingJobsMutex.Lock();
responseJSON = *waitingJobs[id];
delete(waitingJobs, id)
waitingJobsMutex.Unlock();
err = nil;
return;
}
/* Converts a request into the correct binary arguments */
func getArguments(path string, body []byte) []string {
return nil // For now
/* Handles putting a response into waitingJobs. Returns false on error */
func Response(body string) {
var unmarshaledJSON any;
json.Unmarshal([]byte(body), &unmarshaledJSON);
unmarshaledJSONMap, ok := unmarshaledJSON.(map[string]any)
if !ok {return}
val, ok := unmarshaledJSONMap["id"];
if !ok {return}
id, ok := val.(string)
if !ok {return}
// Write response into
waitingJobsMutex.Lock();
waitingJobs[id] = &body;
waitingJobsMutex.Unlock();
}
func genID() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {return ""}
return base64.RawURLEncoding.EncodeToString(b)
}