endpoint.go 11 KB

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