endpoint.go 11 KB

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