44	"bytes" 
55	"encoding/json" 
66	"fmt" 
7- 	"github.com/CloudImpl-Inc/next-coder-sdk/client/db" 
87	"github.com/CloudImpl-Inc/next-coder-sdk/polycode" 
98	"net/http" 
109	"time" 
@@ -20,32 +19,54 @@ const (
2019
2120type  TaskStatus  int8 
2221
23- type  Request  struct  {
24- 	Context  RemoteTaskContext 
25- 	Input    polycode.TaskInput 
22+ type  StartAppRequest  struct  {
23+ 	ClientPort  int  `json:"clientPort"` 
2624}
2725
28- type  Output  struct  {
29- 	SessionId  string  `json:"sessionId"` 
26+ type  ExecRequest  struct  {
27+ 	ServiceId   string                `json:"serviceId"` 
28+ 	EntryPoint  string                `json:"entryPoint"` 
29+ 	Options     polycode.TaskOptions  `json:"options"` 
30+ 	Input       polycode.TaskInput    `json:"input"` 
3031}
3132
32- type  UrlCache  struct  {
33- 	serviceIdUrl  string 
34- 	//callTaskUrl  string 
33+ // PutRequest represents the JSON structure for put operations 
34+ type  PutRequest  struct  {
35+ 	Action      string                  `json:"action"` 
36+ 	Collection  string                  `json:"collection"` 
37+ 	Key         string                  `json:"key"` 
38+ 	Item        map [string ]interface {} `json:"item"` 
39+ }
40+ 
41+ // QueryRequest represents the JSON structure for query operations 
42+ type  QueryRequest  struct  {
43+ 	Collection  string         `json:"collection"` 
44+ 	Key         string         `json:"key"` 
45+ 	Filter      string         `json:"filter"` 
46+ 	Args        []interface {} `json:"args"` 
47+ 	Limit       int            `json:"limit"` 
48+ }
49+ 
50+ // GetFileRequest represents the JSON structure for get file operations 
51+ type  GetFileRequest  struct  {
52+ 	Key  string  `json:"key"` 
53+ }
54+ 
55+ // GetFileResponse represents the JSON structure for get file response 
56+ type  GetFileResponse  struct  {
57+ 	Content  string  `json:"content"` 
58+ }
59+ 
60+ // PutFileRequest represents the JSON structure for put file operations 
61+ type  PutFileRequest  struct  {
62+ 	Key      string  `json:"key"` 
63+ 	Content  string  `json:"content"` 
3564}
3665
3766// ServiceClient is a reusable client for calling the service API 
3867type  ServiceClient  struct  {
3968	httpClient  * http.Client 
4069	baseURL     string 
41- 	urlCache    UrlCache 
42- }
43- 
44- func  CreateTaskCompleteEvent (output  polycode.TaskOutput , tx  * db.Tx ) * TaskCompleteEvent  {
45- 	return  & TaskCompleteEvent {
46- 		Tx :     tx ,
47- 		Output : output ,
48- 	}
4970}
5071
5172// NewServiceClient creates a new ServiceClient with a reusable HTTP client 
@@ -55,154 +76,123 @@ func NewServiceClient(baseURL string) *ServiceClient {
5576			Timeout : time .Second  *  30 , // Set a reasonable timeout for HTTP requests 
5677		},
5778		baseURL : baseURL ,
58- 		urlCache : UrlCache {
59- 			serviceIdUrl : fmt .Sprintf ("%s/system/service/id" , baseURL ),
60- 			//callTaskUrl:  fmt.Sprintf("%s/system/task/%s/%s/call", baseURL), 
61- 		},
6279	}
6380}
6481
65- //func (sc *ServiceClient) startTask(context *TaskContext, input *polycode.TaskInput) (string, error) { 
66- // 
67- //	req := Request{ 
68- //		Context: context, 
69- //		Input:   input, 
70- //	} 
71- //	b, err := json.Marshal(req) 
72- //	if err != nil { 
73- //		return "", fmt.Errorf("failed to marshal JSON: %w", err) 
74- //	} 
75- //	resp, err := sc.httpClient.Post(fmt.Sprintf("%s/system/task/init", sc.baseURL), "application/json", bytes.NewBuffer(b)) 
76- //	if err != nil { 
77- //		return "", fmt.Errorf("failed to make HTTP request: %w", err) 
78- //	} 
79- //	defer resp.Body.Close() 
80- // 
81- //	// Check if the response status code is 200 OK 
82- //	if resp.StatusCode != http.StatusOK { 
83- //		return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode) 
84- //	} 
85- // 
86- //	output := &Output{} 
87- //	if err := json.NewDecoder(resp.Body).Decode(output); err != nil { 
88- //		return "", fmt.Errorf("failed to decode JSON response: %w", err) 
89- //	} 
90- //	return output.SessionId, nil 
91- //} 
92- 
82+ // StartApp starts the app 
9383func  (sc  * ServiceClient ) StartApp (req  StartAppRequest ) error  {
84+ 	return  executeApiWithoutResponse (sc .httpClient , sc .baseURL , "" , "v1/context/app/start" , req )
85+ }
9486
95- 	b , err  :=  json .Marshal (req )
87+ // ExecService executes a service with the given request 
88+ func  (sc  * ServiceClient ) ExecService (sessionId  string , req  ExecRequest ) (polycode.TaskOutput , error ) {
89+ 	var  res  polycode.TaskOutput 
90+ 	err  :=  executeApiWithResponse (sc .httpClient , sc .baseURL , sessionId , "v1/context/service/exec" , req , & res )
9691	if  err  !=  nil  {
97- 		return  fmt .Errorf ("failed to marshal JSON: %w" , err )
92+ 		return  polycode.TaskOutput {}, err 
93+ 	}
94+ 
95+ 	if  res .IsAsync  {
96+ 		panic (ErrTaskInProgress )
9897	}
99- 	resp , err  :=  sc .httpClient .Post (fmt .Sprintf ("%s/v1/system/app/start" , sc .baseURL ), "application/json" , bytes .NewBuffer (b ))
98+ 	return  res , nil 
99+ }
100+ 
101+ // GetItem gets an item from the database 
102+ func  (sc  * ServiceClient ) GetItem (sessionId  string , req  QueryRequest ) (map [string ]interface {}, error ) {
103+ 	var  res  map [string ]interface {}
104+ 	err  :=  executeApiWithResponse (sc .httpClient , sc .baseURL , sessionId , "v1/context/db/get" , req , & res )
100105	if  err  !=  nil  {
101- 		return  fmt . Errorf ( "failed to make HTTP request: %w" , err ) 
106+ 		return  nil , err 
102107	}
103- 	defer  resp .Body .Close ()
108+ 	return  res , nil 
109+ }
104110
105- 	// Check if the response status code is 200 OK 
106- 	if  resp .StatusCode  !=  http .StatusOK  {
107- 		return  fmt .Errorf ("unexpected status code: %d" , resp .StatusCode )
111+ // QueryItems queries items from the database 
112+ func  (sc  * ServiceClient ) QueryItems (sessionId  string , req  QueryRequest ) ([]map [string ]interface {}, error ) {
113+ 	var  res  []map [string ]interface {}
114+ 	err  :=  executeApiWithResponse (sc .httpClient , sc .baseURL , sessionId , "v1/context/db/query" , req , & res )
115+ 	if  err  !=  nil  {
116+ 		return  nil , err 
108117	}
109- 	return  nil 
118+ 	return  res , nil 
119+ }
120+ 
121+ // PutItem puts an item into the database 
122+ func  (sc  * ServiceClient ) PutItem (sessionId  string , req  PutRequest ) error  {
123+ 	return  executeApiWithoutResponse (sc .httpClient , sc .baseURL , sessionId , "v1/context/db/put" , req )
110124}
111125
112- func  (sc  * ServiceClient ) completeTask (sessionId  string , completeEvent  * TaskCompleteEvent ) error  {
113- 	b , err  :=  json .Marshal (completeEvent )
126+ // GetFile gets a file from the file store 
127+ func  (sc  * ServiceClient ) GetFile (sessionId  string , req  GetFileRequest ) (GetFileResponse , error ) {
128+ 	var  res  GetFileResponse 
129+ 	err  :=  executeApiWithResponse (sc .httpClient , sc .baseURL , sessionId , "v1/context/file/get" , req , & res )
114130	if  err  !=  nil  {
115- 		return  fmt . Errorf ( "failed to marshal JSON: %w" , err ) 
131+ 		return  GetFileResponse {} , err 
116132	}
117- 	resp , err  :=  sc .httpClient .Post (fmt .Sprintf ("%s/system/tasks/%s/complete" , sc .baseURL , sessionId ), "application/json" , bytes .NewBuffer (b ))
133+ 	return  res , nil 
134+ }
135+ 
136+ // PutFile puts a file into the file store 
137+ func  (sc  * ServiceClient ) PutFile (sessionId  string , req  PutFileRequest ) error  {
138+ 	return  executeApiWithoutResponse (sc .httpClient , sc .baseURL , sessionId , "v1/context/file/put" , req )
139+ }
140+ 
141+ func  executeApiWithoutResponse (httpClient  * http.Client , baseUrl  string , sessionId  string , path  string , req  any ) error  {
142+ 	reqBody , err  :=  json .Marshal (req )
143+ 	if  err  !=  nil  {
144+ 		return  err 
145+ 	}
146+ 
147+ 	httpReq , err  :=  http .NewRequest (http .MethodPost , fmt .Sprintf ("%s/%s" , baseUrl , path ), bytes .NewBuffer (reqBody ))
118148	if  err  !=  nil  {
119- 		return  fmt .Errorf ("failed to make HTTP request: %w" , err )
149+ 		return  err 
150+ 	}
151+ 	httpReq .Header .Set ("Content-Type" , "application/json" )
152+ 	httpReq .Header .Set ("x-polycode-session-id" , sessionId )
153+ 
154+ 	resp , err  :=  httpClient .Do (httpReq )
155+ 	if  err  !=  nil  {
156+ 		return  err 
120157	}
121158	defer  resp .Body .Close ()
122159
123- 	// Check if the response status code is 200 OK 
124160	if  resp .StatusCode  !=  http .StatusOK  {
125- 		return  fmt .Errorf ("unexpected status code : %d " , resp .StatusCode )
161+ 		return  fmt .Errorf ("failed to put file, status : %v " , resp .Status )
126162	}
163+ 
127164	return  nil 
128165}
129166
130- func  (sc  * ServiceClient ) ExecTask (ctx  RemoteTaskContext , method  string , input  polycode.TaskInput ) (* polycode.TaskOutput , error ) {
131- 
132- 	req  :=  Request {
133- 		Context : ctx ,
134- 		Input :   input ,
167+ func  executeApiWithResponse [T  any ](httpClient  * http.Client , baseUrl  string , sessionId  string , path  string , req  any , res  * T ) error  {
168+ 	reqBody , err  :=  json .Marshal (req )
169+ 	if  err  !=  nil  {
170+ 		return  err 
135171	}
136172
137- 	b , err  :=  json . Marshal ( req )
173+ 	httpReq , err  :=  http . NewRequest ( http . MethodPost ,  fmt . Sprintf ( "%s/%s" ,  baseUrl ,  path ),  bytes . NewBuffer ( reqBody ) )
138174	if  err  !=  nil  {
139- 		return  nil ,  fmt . Errorf ( "failed to marshal JSON: %w" ,  err ) 
175+ 		return  err 
140176	}
141- 	// Make the HTTP POST request 
142- 	resp , err  :=  sc .httpClient .Post (fmt .Sprintf ("%s/v1/system/tasks/%s/exec" , sc .baseURL , ctx .SessionId ), "application/json" , bytes .NewBuffer (b ))
177+ 	httpReq .Header .Set ("Content-Type" , "application/json" )
178+ 	httpReq .Header .Set ("x-polycode-session-id" , sessionId )
179+ 
180+ 	resp , err  :=  httpClient .Do (httpReq )
143181	if  err  !=  nil  {
144- 		return  nil ,  fmt . Errorf ( "failed to make HTTP request: %w" ,  err ) 
182+ 		return  err 
145183	}
146184	defer  resp .Body .Close ()
147185
148- 	// Check if the response status code is 200 OK 
149186	if  resp .StatusCode  !=  http .StatusOK  {
150- 		return  nil ,  fmt .Errorf ("unexpected status code : %d " , resp .StatusCode )
187+ 		return  fmt .Errorf ("failed to put file, status : %v " , resp .Status )
151188	}
152189
153- 	output  :=  & polycode.TaskOutput {}
154- 	if  err  :=  json .NewDecoder (resp .Body ).Decode (output ); err  !=  nil  {
155- 		return  nil , fmt .Errorf ("failed to decode JSON response: %w" , err )
190+ 	if  res  !=  nil  {
191+ 		err  =  json .NewDecoder (resp .Body ).Decode (res )
192+ 		if  err  !=  nil  {
193+ 			return  err 
194+ 		}
156195	}
157196
158- 	if  output .IsAsync  {
159- 		panic (ErrTaskInProgress ) //task in progress panic 
160- 	}
161- 	// Return the taskId from the response 
162- 	return  output , nil 
163- }
164- 
165- //func (sc *ServiceClient) dbCommit(sessionId string, request *TxRequest) error { 
166- // 
167- //	b, err := json.Marshal(request) 
168- //	if err != nil { 
169- //		return fmt.Errorf("failed to marshal JSON: %w", err) 
170- //	} 
171- //	resp, err := sc.httpClient.Post(fmt.Sprintf("%s/system/%s/db/commit", sc.baseURL, sessionId), "application/json", bytes.NewBuffer(b)) 
172- //	if err != nil { 
173- //		return fmt.Errorf("failed to make HTTP request: %w", err) 
174- //	} 
175- //	defer resp.Body.Close() 
176- // 
177- //	// Check if the response status code is 200 OK 
178- //	if resp.StatusCode != http.StatusOK { 
179- //		return fmt.Errorf("unexpected status code: %d", resp.StatusCode) 
180- //	} 
181- //	return nil 
182- //} 
183- 
184- //func (sc *ServiceClient) dbGet(sessionId string, request DBAction) (string, error) { 
185- // 
186- //	b, err := json.Marshal(request) 
187- //	if err != nil { 
188- //		return "", fmt.Errorf("failed to marshal JSON: %w", err) 
189- //	} 
190- //	resp, err := sc.httpClient.Post(fmt.Sprintf("%s/v1/system/%s/db/get", sc.baseURL, sessionId), "application/json", bytes.NewBuffer(b)) 
191- //	if err != nil { 
192- //		return "", fmt.Errorf("failed to make HTTP request: %w", err) 
193- //	} 
194- //	defer resp.Body.Close() 
195- // 
196- //	// Check if the response status code is 200 OK 
197- //	if resp.StatusCode != http.StatusOK { 
198- //		return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode) 
199- //	} 
200- // 
201- //	//return the response body as a string 
202- //	respBody := &bytes.Buffer{} 
203- //	_, err = respBody.ReadFrom(resp.Body) 
204- //	if err != nil { 
205- //		return "", fmt.Errorf("failed to read response body: %w", err) 
206- //	} 
207- //	return respBody.String(), nil 
208- //} 
197+ 	return  nil 
198+ }
0 commit comments