endpoint.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "sync/atomic"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/langgenius/dify-plugin-daemon/internal/core/dify_invocation"
  13. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_daemon"
  14. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_daemon/access_types"
  15. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager"
  16. "github.com/langgenius/dify-plugin-daemon/internal/core/session_manager"
  17. "github.com/langgenius/dify-plugin-daemon/internal/db"
  18. "github.com/langgenius/dify-plugin-daemon/internal/service/install_service"
  19. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  20. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  21. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/requests"
  22. "github.com/langgenius/dify-plugin-daemon/internal/types/exception"
  23. "github.com/langgenius/dify-plugin-daemon/internal/types/models"
  24. "github.com/langgenius/dify-plugin-daemon/internal/utils/encryption"
  25. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  26. )
  27. func Endpoint(
  28. ctx *gin.Context,
  29. endpoint *models.Endpoint,
  30. pluginInstallation *models.PluginInstallation,
  31. path string,
  32. ) {
  33. if !endpoint.Enabled {
  34. ctx.JSON(404, exception.NotFoundError(errors.New("endpoint not found")).ToResponse())
  35. return
  36. }
  37. req := ctx.Request.Clone(context.Background())
  38. req.URL.Path = path
  39. // read request body until complete, max 10MB
  40. body, err := io.ReadAll(io.LimitReader(req.Body, 10*1024*1024))
  41. if err != nil {
  42. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  43. return
  44. }
  45. // replace with a new reader
  46. req.Body = io.NopCloser(bytes.NewReader(body))
  47. req.ContentLength = int64(len(body))
  48. req.TransferEncoding = nil
  49. // remove ip traces for security
  50. req.Header.Del("X-Forwarded-For")
  51. req.Header.Del("X-Real-IP")
  52. req.Header.Del("X-Forwarded")
  53. req.Header.Del("X-Original-Forwarded-For")
  54. req.Header.Del("X-Original-Url")
  55. req.Header.Del("X-Original-Host")
  56. var buffer bytes.Buffer
  57. err = req.Write(&buffer)
  58. if err != nil {
  59. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  60. return
  61. }
  62. identifier, err := plugin_entities.NewPluginUniqueIdentifier(pluginInstallation.PluginUniqueIdentifier)
  63. if err != nil {
  64. ctx.JSON(400, exception.PluginUniqueIdentifierError(err).ToResponse())
  65. return
  66. }
  67. // fetch plugin
  68. manager := plugin_manager.Manager()
  69. runtime, err := manager.Get(identifier)
  70. if err != nil {
  71. ctx.JSON(404, exception.ErrPluginNotFound().ToResponse())
  72. return
  73. }
  74. // fetch endpoint declaration
  75. endpointDeclaration := runtime.Configuration().Endpoint
  76. if endpointDeclaration == nil {
  77. ctx.JSON(404, exception.ErrPluginNotFound().ToResponse())
  78. return
  79. }
  80. // decrypt settings
  81. settings, err := manager.BackwardsInvocation().InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  82. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  83. TenantId: endpoint.TenantID,
  84. UserId: "",
  85. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  86. },
  87. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  88. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  89. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  90. Identity: endpoint.ID,
  91. Data: endpoint.Settings,
  92. Config: endpointDeclaration.Settings,
  93. },
  94. })
  95. if err != nil {
  96. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  97. return
  98. }
  99. session := session_manager.NewSession(
  100. session_manager.NewSessionPayload{
  101. TenantID: endpoint.TenantID,
  102. UserID: "",
  103. PluginUniqueIdentifier: identifier,
  104. ClusterID: ctx.GetString("cluster_id"),
  105. InvokeFrom: access_types.PLUGIN_ACCESS_TYPE_ENDPOINT,
  106. Action: access_types.PLUGIN_ACCESS_ACTION_INVOKE_ENDPOINT,
  107. Declaration: runtime.Configuration(),
  108. BackwardsInvocation: manager.BackwardsInvocation(),
  109. IgnoreCache: false,
  110. EndpointID: &endpoint.ID,
  111. },
  112. )
  113. defer session.Close(session_manager.CloseSessionPayload{
  114. IgnoreCache: false,
  115. })
  116. session.BindRuntime(runtime)
  117. statusCode, headers, response, err := plugin_daemon.InvokeEndpoint(
  118. session, &requests.RequestInvokeEndpoint{
  119. RawHttpRequest: hex.EncodeToString(buffer.Bytes()),
  120. Settings: settings,
  121. },
  122. )
  123. if err != nil {
  124. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  125. return
  126. }
  127. defer response.Close()
  128. done := make(chan bool)
  129. closed := new(int32)
  130. ctx.Status(statusCode)
  131. for k, v := range *headers {
  132. if len(v) > 0 {
  133. ctx.Writer.Header().Set(k, v[0])
  134. }
  135. }
  136. close := func() {
  137. if atomic.CompareAndSwapInt32(closed, 0, 1) {
  138. close(done)
  139. }
  140. }
  141. defer close()
  142. routine.Submit(map[string]string{
  143. "module": "service",
  144. "function": "Endpoint",
  145. }, func() {
  146. defer close()
  147. for response.Next() {
  148. chunk, err := response.Read()
  149. if err != nil {
  150. ctx.Writer.Write([]byte(err.Error()))
  151. ctx.Writer.Flush()
  152. return
  153. }
  154. ctx.Writer.Write(chunk)
  155. ctx.Writer.Flush()
  156. }
  157. })
  158. select {
  159. case <-ctx.Writer.CloseNotify():
  160. case <-done:
  161. case <-time.After(240 * time.Second):
  162. ctx.JSON(500, exception.InternalServerError(errors.New("killed by timeout")).ToResponse())
  163. }
  164. }
  165. func EnableEndpoint(endpoint_id string, tenant_id string) *entities.Response {
  166. endpoint, err := db.GetOne[models.Endpoint](
  167. db.Equal("id", endpoint_id),
  168. db.Equal("tenant_id", tenant_id),
  169. )
  170. if err != nil {
  171. return exception.NotFoundError(errors.New("endpoint not found")).ToResponse()
  172. }
  173. endpoint.Enabled = true
  174. if err := install_service.EnabledEndpoint(&endpoint); err != nil {
  175. return exception.InternalServerError(errors.New("failed to enable endpoint")).ToResponse()
  176. }
  177. return entities.NewSuccessResponse(true)
  178. }
  179. func DisableEndpoint(endpoint_id string, tenant_id string) *entities.Response {
  180. endpoint, err := db.GetOne[models.Endpoint](
  181. db.Equal("id", endpoint_id),
  182. db.Equal("tenant_id", tenant_id),
  183. )
  184. if err != nil {
  185. return exception.NotFoundError(errors.New("Endpoint not found")).ToResponse()
  186. }
  187. endpoint.Enabled = false
  188. if err := install_service.DisabledEndpoint(&endpoint); err != nil {
  189. return exception.InternalServerError(errors.New("failed to disable endpoint")).ToResponse()
  190. }
  191. return entities.NewSuccessResponse(true)
  192. }
  193. func ListEndpoints(tenant_id string, page int, page_size int) *entities.Response {
  194. endpoints, err := db.GetAll[models.Endpoint](
  195. db.Equal("tenant_id", tenant_id),
  196. db.OrderBy("created_at", true),
  197. db.Page(page, page_size),
  198. )
  199. if err != nil {
  200. return exception.InternalServerError(fmt.Errorf("failed to list endpoints: %v", err)).ToResponse()
  201. }
  202. manager := plugin_manager.Manager()
  203. if manager == nil {
  204. return exception.InternalServerError(errors.New("failed to get plugin manager")).ToResponse()
  205. }
  206. // decrypt settings
  207. for i, endpoint := range endpoints {
  208. pluginInstallation, err := db.GetOne[models.PluginInstallation](
  209. db.Equal("plugin_id", endpoint.PluginID),
  210. db.Equal("tenant_id", tenant_id),
  211. )
  212. if err != nil {
  213. // use empty settings and declaration for uninstalled plugins
  214. endpoint.Settings = map[string]any{}
  215. endpoint.Declaration = &plugin_entities.EndpointProviderDeclaration{
  216. Settings: []plugin_entities.ProviderConfig{},
  217. Endpoints: []plugin_entities.EndpointDeclaration{},
  218. EndpointFiles: []string{},
  219. }
  220. endpoints[i] = endpoint
  221. continue
  222. }
  223. pluginUniqueIdentifier, err := plugin_entities.NewPluginUniqueIdentifier(
  224. pluginInstallation.PluginUniqueIdentifier,
  225. )
  226. if err != nil {
  227. return exception.PluginUniqueIdentifierError(
  228. fmt.Errorf("failed to parse plugin unique identifier: %v", err),
  229. ).ToResponse()
  230. }
  231. pluginDeclaration, err := manager.GetDeclaration(
  232. pluginUniqueIdentifier,
  233. tenant_id,
  234. plugin_entities.PluginRuntimeType(pluginInstallation.RuntimeType),
  235. )
  236. if err != nil {
  237. return exception.InternalServerError(
  238. fmt.Errorf("failed to get plugin declaration: %v", err),
  239. ).ToResponse()
  240. }
  241. if pluginDeclaration.Endpoint == nil {
  242. return exception.NotFoundError(errors.New("plugin does not have an endpoint")).ToResponse()
  243. }
  244. decryptedSettings, err := manager.BackwardsInvocation().InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  245. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  246. TenantId: tenant_id,
  247. UserId: "",
  248. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  249. },
  250. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  251. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  252. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  253. Identity: endpoint.ID,
  254. Data: endpoint.Settings,
  255. Config: pluginDeclaration.Endpoint.Settings,
  256. },
  257. })
  258. if err != nil {
  259. return exception.InternalServerError(
  260. fmt.Errorf("failed to decrypt settings: %v", err),
  261. ).ToResponse()
  262. }
  263. // mask settings
  264. decryptedSettings = encryption.MaskConfigCredentials(decryptedSettings, pluginDeclaration.Endpoint.Settings)
  265. endpoint.Settings = decryptedSettings
  266. endpoint.Declaration = pluginDeclaration.Endpoint
  267. endpoints[i] = endpoint
  268. }
  269. return entities.NewSuccessResponse(endpoints)
  270. }
  271. func ListPluginEndpoints(tenant_id string, plugin_id string, page int, page_size int) *entities.Response {
  272. endpoints, err := db.GetAll[models.Endpoint](
  273. db.Equal("plugin_id", plugin_id),
  274. db.Equal("tenant_id", tenant_id),
  275. db.OrderBy("created_at", true),
  276. db.Page(page, page_size),
  277. )
  278. if err != nil {
  279. return exception.InternalServerError(
  280. fmt.Errorf("failed to list endpoints: %v", err),
  281. ).ToResponse()
  282. }
  283. manager := plugin_manager.Manager()
  284. if manager == nil {
  285. return exception.InternalServerError(
  286. errors.New("failed to get plugin manager"),
  287. ).ToResponse()
  288. }
  289. // decrypt settings
  290. for i, endpoint := range endpoints {
  291. // get installation
  292. pluginInstallation, err := db.GetOne[models.PluginInstallation](
  293. db.Equal("plugin_id", plugin_id),
  294. db.Equal("tenant_id", tenant_id),
  295. )
  296. if err != nil {
  297. return exception.NotFoundError(
  298. fmt.Errorf("failed to find plugin installation: %v", err),
  299. ).ToResponse()
  300. }
  301. pluginUniqueIdentifier, err := plugin_entities.NewPluginUniqueIdentifier(
  302. pluginInstallation.PluginUniqueIdentifier,
  303. )
  304. if err != nil {
  305. return exception.PluginUniqueIdentifierError(
  306. fmt.Errorf("failed to parse plugin unique identifier: %v", err),
  307. ).ToResponse()
  308. }
  309. pluginDeclaration, err := manager.GetDeclaration(
  310. pluginUniqueIdentifier,
  311. tenant_id,
  312. plugin_entities.PluginRuntimeType(pluginInstallation.RuntimeType),
  313. )
  314. if err != nil {
  315. return exception.InternalServerError(
  316. fmt.Errorf("failed to get plugin declaration: %v", err),
  317. ).ToResponse()
  318. }
  319. decryptedSettings, err := manager.BackwardsInvocation().InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  320. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  321. TenantId: tenant_id,
  322. UserId: "",
  323. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  324. },
  325. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  326. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  327. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  328. Identity: endpoint.ID,
  329. Data: endpoint.Settings,
  330. Config: pluginDeclaration.Endpoint.Settings,
  331. },
  332. })
  333. if err != nil {
  334. return exception.InternalServerError(
  335. fmt.Errorf("failed to decrypt settings: %v", err),
  336. ).ToResponse()
  337. }
  338. // mask settings
  339. decryptedSettings = encryption.MaskConfigCredentials(decryptedSettings, pluginDeclaration.Endpoint.Settings)
  340. endpoint.Settings = decryptedSettings
  341. endpoint.Declaration = pluginDeclaration.Endpoint
  342. endpoints[i] = endpoint
  343. }
  344. return entities.NewSuccessResponse(endpoints)
  345. }