externalReqHandler.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. package agi
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. uuid "github.com/satori/go.uuid"
  10. "imuslab.com/arozos/mod/agi/static"
  11. "imuslab.com/arozos/mod/info/logger"
  12. "imuslab.com/arozos/mod/utils"
  13. )
  14. // statsTable is the BoltDB table used to persist endpoint execution statistics.
  15. const statsTable = "ext_agi_stats"
  16. // endpointFormat holds the owner and script path for a registered endpoint.
  17. type endpointFormat struct {
  18. Username string `json:"username"`
  19. Path string `json:"path"`
  20. }
  21. // ExecLog holds the details of a single execution attempt.
  22. type ExecLog struct {
  23. RequestID string `json:"request_id"`
  24. Timestamp int64 `json:"timestamp"`
  25. DurationMs int64 `json:"duration_ms"`
  26. Method string `json:"method"`
  27. Message string `json:"message"`
  28. }
  29. // EndpointStats tracks cumulative statistics for a single serverless endpoint.
  30. type EndpointStats struct {
  31. UUID string `json:"uuid"`
  32. Path string `json:"path"`
  33. TotalExecutions int64 `json:"total_executions"`
  34. SuccessfulExecs int64 `json:"successful_executions"`
  35. FailedExecs int64 `json:"failed_executions"`
  36. TotalExecTimeMs int64 `json:"total_exec_time_ms"`
  37. AvgExecTimeMs float64 `json:"avg_exec_time_ms"`
  38. LastExecutedAt int64 `json:"last_executed_at"`
  39. RecentSuccess []ExecLog `json:"recent_success"`
  40. RecentFailed []ExecLog `json:"recent_failed"`
  41. }
  42. // ── DB helpers ────────────────────────────────────────────────────────────────
  43. // ensureStatsTable creates the stats DB table if it does not yet exist.
  44. func (g *Gateway) ensureStatsTable() {
  45. sysdb := g.Option.UserHandler.GetDatabase()
  46. if !sysdb.TableExists(statsTable) {
  47. sysdb.NewTable(statsTable)
  48. }
  49. }
  50. // loadStatsFromDB reads persisted EndpointStats for one UUID from BoltDB.
  51. // Returns nil when no record exists or the data cannot be parsed.
  52. // Must NOT be called while holding g.statsMux.
  53. func (g *Gateway) loadStatsFromDB(endpointUUID string) *EndpointStats {
  54. sysdb := g.Option.UserHandler.GetDatabase()
  55. if !sysdb.TableExists(statsTable) {
  56. return nil
  57. }
  58. if !sysdb.KeyExists(statsTable, endpointUUID) {
  59. return nil
  60. }
  61. // The DB stores values as JSON-encoded strings; Read() decodes one layer.
  62. rawJSON := ""
  63. if err := sysdb.Read(statsTable, endpointUUID, &rawJSON); err != nil {
  64. return nil
  65. }
  66. var s EndpointStats
  67. if err := json.Unmarshal([]byte(rawJSON), &s); err != nil {
  68. return nil
  69. }
  70. // Ensure slice fields are never nil (avoids JSON "null" in responses).
  71. if s.RecentSuccess == nil {
  72. s.RecentSuccess = []ExecLog{}
  73. }
  74. if s.RecentFailed == nil {
  75. s.RecentFailed = []ExecLog{}
  76. }
  77. return &s
  78. }
  79. // saveStatsToDB persists the pre-marshalled stats JSON for one endpoint.
  80. // Must NOT be called while holding g.statsMux (to avoid lock contention on I/O).
  81. func (g *Gateway) saveStatsToDB(endpointUUID string, jsonBytes []byte) {
  82. g.ensureStatsTable()
  83. sysdb := g.Option.UserHandler.GetDatabase()
  84. sysdb.Write(statsTable, endpointUUID, string(jsonBytes))
  85. }
  86. // deleteStatsFromDB removes persisted stats for one endpoint.
  87. func (g *Gateway) deleteStatsFromDB(endpointUUID string) {
  88. sysdb := g.Option.UserHandler.GetDatabase()
  89. if sysdb.TableExists(statsTable) {
  90. sysdb.Delete(statsTable, endpointUUID)
  91. }
  92. }
  93. // ── Core execution tracking ───────────────────────────────────────────────────
  94. // recordExecution updates in-memory stats for endpointUUID after one execution
  95. // and then persists them to BoltDB. Safe for concurrent use.
  96. func (g *Gateway) recordExecution(endpointUUID, path, requestID, method string, durationMs int64, execErr error) {
  97. g.statsMux.Lock()
  98. stats, exists := g.endpointStats[endpointUUID]
  99. if !exists {
  100. // Cold-start: try to restore from the database before creating a blank entry.
  101. // loadStatsFromDB must be called without the lock (it doesn't touch the map),
  102. // but here we release and re-acquire to keep the load outside the lock window.
  103. g.statsMux.Unlock()
  104. loaded := g.loadStatsFromDB(endpointUUID)
  105. g.statsMux.Lock()
  106. // Re-check in case another goroutine populated it while we were loading.
  107. if stats, exists = g.endpointStats[endpointUUID]; !exists {
  108. if loaded != nil {
  109. stats = loaded
  110. } else {
  111. stats = &EndpointStats{
  112. UUID: endpointUUID,
  113. Path: path,
  114. RecentSuccess: []ExecLog{},
  115. RecentFailed: []ExecLog{},
  116. }
  117. }
  118. g.endpointStats[endpointUUID] = stats
  119. }
  120. }
  121. stats.TotalExecutions++
  122. stats.TotalExecTimeMs += durationMs
  123. stats.LastExecutedAt = time.Now().Unix()
  124. stats.AvgExecTimeMs = float64(stats.TotalExecTimeMs) / float64(stats.TotalExecutions)
  125. entry := ExecLog{
  126. RequestID: requestID,
  127. Timestamp: time.Now().Unix(),
  128. DurationMs: durationMs,
  129. Method: method,
  130. }
  131. if execErr != nil {
  132. stats.FailedExecs++
  133. entry.Message = execErr.Error()
  134. stats.RecentFailed = append([]ExecLog{entry}, stats.RecentFailed...)
  135. if len(stats.RecentFailed) > 10 {
  136. stats.RecentFailed = stats.RecentFailed[:10]
  137. }
  138. } else {
  139. stats.SuccessfulExecs++
  140. entry.Message = "Execution successful"
  141. stats.RecentSuccess = append([]ExecLog{entry}, stats.RecentSuccess...)
  142. if len(stats.RecentSuccess) > 10 {
  143. stats.RecentSuccess = stats.RecentSuccess[:10]
  144. }
  145. }
  146. // Marshal while still holding the lock so we capture a consistent snapshot.
  147. jsonBytes, _ := json.Marshal(stats)
  148. g.statsMux.Unlock()
  149. // DB write outside the lock to avoid holding it during I/O.
  150. g.saveStatsToDB(endpointUUID, jsonBytes)
  151. }
  152. // ── HTTP handlers ─────────────────────────────────────────────────────────────
  153. // ExtAPIHandler handles incoming requests from external services via
  154. // /api/remote/{UUID}.
  155. func (g *Gateway) ExtAPIHandler(w http.ResponseWriter, r *http.Request) {
  156. sysdb := g.Option.UserHandler.GetDatabase()
  157. if !sysdb.TableExists("external_agi") {
  158. http.Error(w, "invalid API request", http.StatusBadRequest)
  159. return
  160. }
  161. requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
  162. subpathElements := strings.Split(requestURI[1:], "/")
  163. if len(subpathElements) != 3 {
  164. http.Error(w, "invalid API request", http.StatusBadRequest)
  165. return
  166. }
  167. endpointUUID := subpathElements[2]
  168. data, isExist := g.checkIfExternalEndpointExist(endpointUUID)
  169. if !isExist {
  170. http.Error(w, "malformed request: invalid UUID given", http.StatusBadRequest)
  171. return
  172. }
  173. usernameFromDb := data.Username
  174. pathFromDb := data.Path
  175. userInfo, err := g.Option.UserHandler.GetUserInfoFromUsername(usernameFromDb)
  176. if err != nil {
  177. http.Error(w, "invalid request: API author no longer exists", http.StatusBadRequest)
  178. return
  179. }
  180. fsh, realPath, err := static.VirtualPathToRealPath(pathFromDb, userInfo)
  181. if err != nil {
  182. http.Error(w, "invalid request: backend script path cannot be resolved", http.StatusBadRequest)
  183. return
  184. }
  185. if !fsh.FileSystemAbstraction.FileExists(realPath) {
  186. logger.PrintAndLog("Agi", fmt.Sprint("[Remote AGI] ", pathFromDb, " cannot be found on "+realPath), nil)
  187. http.Error(w, "invalid request: backend script not exists", http.StatusBadRequest)
  188. return
  189. }
  190. // Measure wall-clock duration; the returned execID (assigned by the AGI
  191. // runtime) is reused as the request ID for execution log tracing.
  192. start := time.Now()
  193. execID, result, execErr := g.ExecuteAGIScriptAsUser(fsh, realPath, userInfo, w, r)
  194. durationMs := time.Since(start).Milliseconds()
  195. g.recordExecution(endpointUUID, pathFromDb, execID, r.Method, durationMs, execErr)
  196. if execErr != nil {
  197. logger.PrintAndLog("Agi", fmt.Sprintf("[Remote AGI][%s] %s failed to execute: %s", execID, pathFromDb, execErr.Error()), nil)
  198. utils.SendErrorResponse(w, execErr.Error())
  199. return
  200. }
  201. w.Write([]byte(result))
  202. }
  203. // AddExternalEndPoint registers a new serverless endpoint for the current user.
  204. func (g *Gateway) AddExternalEndPoint(w http.ResponseWriter, r *http.Request) {
  205. userInfo, err := g.Option.UserHandler.GetUserInfoFromRequest(w, r)
  206. if err != nil {
  207. utils.SendErrorResponse(w, "User not logged in")
  208. return
  209. }
  210. sysdb := g.Option.UserHandler.GetDatabase()
  211. if !sysdb.TableExists("external_agi") {
  212. sysdb.NewTable("external_agi")
  213. }
  214. path, err := utils.GetPara(r, "path")
  215. if err != nil {
  216. utils.SendErrorResponse(w, "Invalid path given")
  217. return
  218. }
  219. id := uuid.NewV4().String()
  220. var dat endpointFormat
  221. dat.Path = path
  222. dat.Username = userInfo.Username
  223. jsonStr, err := json.Marshal(dat)
  224. if err != nil {
  225. utils.SendErrorResponse(w, "Invalid JSON string: "+err.Error())
  226. return
  227. }
  228. sysdb.Write("external_agi", id, string(jsonStr))
  229. utils.SendJSONResponse(w, "\""+id+"\"")
  230. }
  231. // RemoveExternalEndPoint deletes a registered endpoint by UUID, including its
  232. // persisted statistics.
  233. func (g *Gateway) RemoveExternalEndPoint(w http.ResponseWriter, r *http.Request) {
  234. userInfo, err := g.Option.UserHandler.GetUserInfoFromRequest(w, r)
  235. if err != nil {
  236. utils.SendErrorResponse(w, "User not logged in")
  237. return
  238. }
  239. sysdb := g.Option.UserHandler.GetDatabase()
  240. if !sysdb.TableExists("external_agi") {
  241. sysdb.NewTable("external_agi")
  242. }
  243. endpointUUID, err := utils.GetPara(r, "uuid")
  244. if err != nil {
  245. utils.SendErrorResponse(w, "Invalid uuid given")
  246. return
  247. }
  248. data, isExist := g.checkIfExternalEndpointExist(endpointUUID)
  249. if !isExist {
  250. utils.SendErrorResponse(w, "UUID does not exists in the database!")
  251. return
  252. }
  253. if data.Username != userInfo.Username {
  254. utils.SendErrorResponse(w, "Permission denied")
  255. return
  256. }
  257. // Remove endpoint record and its persisted stats.
  258. sysdb.Delete("external_agi", endpointUUID)
  259. g.deleteStatsFromDB(endpointUUID)
  260. // Clean up in-memory cache.
  261. g.statsMux.Lock()
  262. delete(g.endpointStats, endpointUUID)
  263. g.statsMux.Unlock()
  264. utils.SendOK(w)
  265. }
  266. // ListExternalEndpoint returns all endpoints registered by the current user.
  267. func (g *Gateway) ListExternalEndpoint(w http.ResponseWriter, r *http.Request) {
  268. userInfo, err := g.Option.UserHandler.GetUserInfoFromRequest(w, r)
  269. if err != nil {
  270. utils.SendErrorResponse(w, "User not logged in")
  271. return
  272. }
  273. sysdb := g.Option.UserHandler.GetDatabase()
  274. if !sysdb.TableExists("external_agi") {
  275. sysdb.NewTable("external_agi")
  276. }
  277. dataFromDB := make(map[string]endpointFormat)
  278. entries, err := sysdb.ListTable("external_agi")
  279. if err != nil {
  280. utils.SendErrorResponse(w, "Invalid table")
  281. return
  282. }
  283. for _, keypairs := range entries {
  284. var dataFromResult endpointFormat
  285. rawJSON := ""
  286. endpointUUID := string(keypairs[0])
  287. json.Unmarshal(keypairs[1], &rawJSON)
  288. json.Unmarshal([]byte(rawJSON), &dataFromResult)
  289. if dataFromResult.Username == userInfo.Username {
  290. dataFromDB[endpointUUID] = dataFromResult
  291. }
  292. }
  293. returnJson, err := json.Marshal(dataFromDB)
  294. if err != nil {
  295. utils.SendErrorResponse(w, "Invalid JSON: "+err.Error())
  296. return
  297. }
  298. utils.SendJSONResponse(w, string(returnJson))
  299. }
  300. // GetEndpointStats returns execution statistics for all endpoints owned by the
  301. // current user. For each endpoint the server checks the in-memory cache first;
  302. // on a cache miss it loads from BoltDB so that stats survive process restarts.
  303. // Endpoints that have never been called are included with zeroed counters.
  304. func (g *Gateway) GetEndpointStats(w http.ResponseWriter, r *http.Request) {
  305. userInfo, err := g.Option.UserHandler.GetUserInfoFromRequest(w, r)
  306. if err != nil {
  307. utils.SendErrorResponse(w, "User not logged in")
  308. return
  309. }
  310. sysdb := g.Option.UserHandler.GetDatabase()
  311. if !sysdb.TableExists("external_agi") {
  312. utils.SendJSONResponse(w, "{}")
  313. return
  314. }
  315. entries, err := sysdb.ListTable("external_agi")
  316. if err != nil {
  317. utils.SendErrorResponse(w, "Invalid table")
  318. return
  319. }
  320. // Collect the UUIDs that belong to this user before touching the lock.
  321. type epEntry struct {
  322. uuid string
  323. path string
  324. }
  325. var userEndpoints []epEntry
  326. for _, keypairs := range entries {
  327. var ep endpointFormat
  328. rawJSON := ""
  329. endpointUUID := string(keypairs[0])
  330. json.Unmarshal(keypairs[1], &rawJSON)
  331. json.Unmarshal([]byte(rawJSON), &ep)
  332. if ep.Username == userInfo.Username {
  333. userEndpoints = append(userEndpoints, epEntry{endpointUUID, ep.Path})
  334. }
  335. }
  336. // For each endpoint: serve from memory, fall back to DB, or return zeros.
  337. // We use a write lock because a DB-load may populate the memory cache.
  338. g.statsMux.Lock()
  339. result := make(map[string]*EndpointStats, len(userEndpoints))
  340. for _, ep := range userEndpoints {
  341. if stats, exists := g.endpointStats[ep.uuid]; exists {
  342. result[ep.uuid] = stats
  343. } else {
  344. // Not in memory — try the database.
  345. g.statsMux.Unlock()
  346. dbStats := g.loadStatsFromDB(ep.uuid)
  347. g.statsMux.Lock()
  348. // Re-check after re-acquiring the lock.
  349. if stats, exists = g.endpointStats[ep.uuid]; exists {
  350. result[ep.uuid] = stats
  351. } else if dbStats != nil {
  352. g.endpointStats[ep.uuid] = dbStats
  353. result[ep.uuid] = dbStats
  354. } else {
  355. result[ep.uuid] = &EndpointStats{
  356. UUID: ep.uuid,
  357. Path: ep.path,
  358. RecentSuccess: []ExecLog{},
  359. RecentFailed: []ExecLog{},
  360. }
  361. }
  362. }
  363. }
  364. g.statsMux.Unlock()
  365. returnJson, err := json.Marshal(result)
  366. if err != nil {
  367. utils.SendErrorResponse(w, "Invalid JSON: "+err.Error())
  368. return
  369. }
  370. utils.SendJSONResponse(w, string(returnJson))
  371. }
  372. func (g *Gateway) checkIfExternalEndpointExist(endpointUUID string) (endpointFormat, bool) {
  373. sysdb := g.Option.UserHandler.GetDatabase()
  374. if !sysdb.TableExists("external_agi") {
  375. sysdb.NewTable("external_agi")
  376. }
  377. var dat endpointFormat
  378. if !sysdb.KeyExists("external_agi", endpointUUID) {
  379. return dat, false
  380. }
  381. jsonData := ""
  382. sysdb.Read("external_agi", endpointUUID, &jsonData)
  383. json.Unmarshal([]byte(jsonData), &dat)
  384. return dat, true
  385. }