install_to_local.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package plugin_manager
  2. import (
  3. "time"
  4. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  5. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  6. "github.com/langgenius/dify-plugin-daemon/internal/utils/stream"
  7. )
  8. // InstallToLocal installs a plugin to local
  9. func (p *PluginManager) InstallToLocal(
  10. plugin_unique_identifier plugin_entities.PluginUniqueIdentifier,
  11. source string,
  12. meta map[string]any,
  13. ) (
  14. *stream.Stream[PluginInstallResponse], error,
  15. ) {
  16. package_file, err := p.packageBucket.Get(plugin_unique_identifier.String())
  17. if err != nil {
  18. return nil, err
  19. }
  20. err = p.installedBucket.Save(plugin_unique_identifier, package_file)
  21. if err != nil {
  22. return nil, err
  23. }
  24. runtime, launched_chan, err := p.launchLocal(plugin_unique_identifier)
  25. if err != nil {
  26. return nil, err
  27. }
  28. response := stream.NewStream[PluginInstallResponse](128)
  29. routine.Submit(func() {
  30. defer response.Close()
  31. ticker := time.NewTicker(time.Second * 5) // check heartbeat every 5 seconds
  32. defer ticker.Stop()
  33. timer := time.NewTimer(time.Second * 240) // timeout after 240 seconds
  34. defer timer.Stop()
  35. for {
  36. select {
  37. case <-ticker.C:
  38. // heartbeat
  39. response.Write(PluginInstallResponse{
  40. Event: PluginInstallEventInfo,
  41. Data: "Installing",
  42. })
  43. case <-timer.C:
  44. // timeout
  45. response.Write(PluginInstallResponse{
  46. Event: PluginInstallEventInfo,
  47. Data: "Timeout",
  48. })
  49. runtime.Stop()
  50. return
  51. case <-launched_chan:
  52. // launched
  53. if err != nil {
  54. response.Write(PluginInstallResponse{
  55. Event: PluginInstallEventError,
  56. Data: err.Error(),
  57. })
  58. runtime.Stop()
  59. return
  60. }
  61. response.Write(PluginInstallResponse{
  62. Event: PluginInstallEventDone,
  63. Data: "Installed",
  64. })
  65. return
  66. }
  67. }
  68. })
  69. return response, nil
  70. }