endpoint.go 12 KB

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