index.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package stream
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "time"
  6. "github.com/0xJacky/Nginx-UI/internal/cache"
  7. "github.com/0xJacky/Nginx-UI/internal/upstream"
  8. )
  9. type Index struct {
  10. Path string
  11. Content string
  12. ProxyTargets []upstream.ProxyTarget
  13. }
  14. var (
  15. IndexedStreams = make(map[string]*Index)
  16. )
  17. func GetIndexedStream(path string) *Index {
  18. if stream, ok := IndexedStreams[path]; ok {
  19. return stream
  20. }
  21. return &Index{}
  22. }
  23. func init() {
  24. cache.RegisterCallback("stream.scanForStream", scanForStream)
  25. }
  26. func scanForStream(configPath string, content []byte) error {
  27. // Only process stream configuration files
  28. if !isStreamConfig(configPath) {
  29. return nil
  30. }
  31. streamIndex := Index{
  32. Path: configPath,
  33. Content: string(content),
  34. ProxyTargets: []upstream.ProxyTarget{},
  35. }
  36. // Parse proxy targets from the configuration content with timeout protection
  37. done := make(chan []upstream.ProxyTarget, 1)
  38. go func() {
  39. targets := upstream.ParseProxyTargetsFromRawContent(string(content))
  40. done <- targets
  41. }()
  42. select {
  43. case targets := <-done:
  44. streamIndex.ProxyTargets = targets
  45. // Only store if we found proxy targets
  46. if len(streamIndex.ProxyTargets) > 0 {
  47. IndexedStreams[filepath.Base(configPath)] = &streamIndex
  48. }
  49. case <-time.After(2 * time.Second):
  50. // Timeout protection - skip this file's stream processing
  51. // This prevents the callback from blocking indefinitely
  52. return nil
  53. }
  54. return nil
  55. }
  56. // isStreamConfig checks if the config path is a stream configuration
  57. func isStreamConfig(configPath string) bool {
  58. return strings.Contains(configPath, "streams-available") ||
  59. strings.Contains(configPath, "streams-enabled")
  60. }