host.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Package nativehost dispatches worker RPC calls onto a native UI thread.
  2. package nativehost
  3. import (
  4. "context"
  5. "encoding/json"
  6. "strings"
  7. "sync"
  8. "clusterflow.dev/cfbrowser/api"
  9. "clusterflow.dev/cfbrowser/internal/capture"
  10. "clusterflow.dev/cfbrowser/protocol"
  11. )
  12. // Backend methods and their completion callbacks must run on the UI thread.
  13. // A method reports its synchronous or asynchronous result exactly once.
  14. type Backend interface {
  15. Configure(api.EngineOptions, func(error))
  16. NewPage(uint64, func(error))
  17. Navigate(uint64, string, string, func(string, error))
  18. Evaluate(uint64, string, func(json.RawMessage, error))
  19. ClosePage(uint64) error
  20. Close()
  21. }
  22. type captureBackend interface {
  23. Capture(uint64, bool, func([]byte, error))
  24. }
  25. type inputBackend interface {
  26. Input(uint64, string, string, float64, float64, func(error))
  27. }
  28. type result struct {
  29. value any
  30. err error
  31. }
  32. type Host struct {
  33. Queue chan func()
  34. backend Backend
  35. options api.EngineOptions
  36. configured bool
  37. configuring bool
  38. pages map[uint64]bool
  39. next uint64
  40. evaluations int
  41. nextEvaluation uint64
  42. pending map[uint64]map[uint64]func()
  43. }
  44. func New(backend Backend) *Host {
  45. return &Host{Queue: make(chan func(), 32), backend: backend, pages: map[uint64]bool{}, pending: map[uint64]map[uint64]func(){}}
  46. }
  47. func (h *Host) call(ctx context.Context, start func(func(any, error))) (any, error) {
  48. if err := ctx.Err(); err != nil {
  49. return nil, err
  50. }
  51. done := make(chan result, 1)
  52. var once sync.Once
  53. complete := func(v any, e error) { once.Do(func() { done <- result{v, e} }) }
  54. select {
  55. case h.Queue <- func() {
  56. if err := ctx.Err(); err != nil {
  57. complete(nil, err)
  58. return
  59. }
  60. start(complete)
  61. }:
  62. case <-ctx.Done():
  63. return nil, ctx.Err()
  64. }
  65. select {
  66. case r := <-done:
  67. return r.value, r.err
  68. case <-ctx.Done():
  69. return nil, ctx.Err()
  70. }
  71. }
  72. func (h *Host) Handle(ctx context.Context, method string, raw json.RawMessage) (any, error) {
  73. if method == "configure" {
  74. var opts api.EngineOptions
  75. if err := json.Unmarshal(raw, &opts); err != nil {
  76. return nil, api.Err("BROWSER_INVALID_ARGUMENT", "invalid engine options")
  77. }
  78. if opts.ViewportWidth == 0 {
  79. opts.ViewportWidth = 1280
  80. }
  81. if opts.ViewportHeight == 0 {
  82. opts.ViewportHeight = 800
  83. }
  84. if opts.ViewportWidth < 1 || opts.ViewportWidth > 4096 || opts.ViewportHeight < 1 || opts.ViewportHeight > 4096 {
  85. return nil, api.Err("BROWSER_INVALID_CONFIG", "viewport must be between 1 and 4096 pixels")
  86. }
  87. return h.call(ctx, func(done func(any, error)) {
  88. if h.configured || h.configuring {
  89. done(nil, api.Err("BROWSER_INVALID_CONFIG", "worker is already configured"))
  90. return
  91. }
  92. h.options = opts
  93. h.configuring = true
  94. h.backend.Configure(opts, func(err error) { h.configuring = false; h.configured = err == nil; done(err == nil, err) })
  95. })
  96. }
  97. var args struct {
  98. Page uint64 `json:"page"`
  99. FullPage bool `json:"fullPage"`
  100. Action string `json:"action"`
  101. Value string `json:"value"`
  102. X float64 `json:"x"`
  103. Y float64 `json:"y"`
  104. URL string `json:"url"`
  105. Op string `json:"op"`
  106. Script string `json:"script"`
  107. }
  108. if method != "page.new" && method != "session.features" {
  109. if err := json.Unmarshal(raw, &args); err != nil {
  110. return nil, api.Err("BROWSER_INVALID_ARGUMENT", "invalid page arguments")
  111. }
  112. }
  113. return h.call(ctx, func(done func(any, error)) {
  114. if !h.configured {
  115. done(nil, api.Err("BROWSER_INVALID_CONFIG", "configure worker first"))
  116. return
  117. }
  118. if method == "session.features" {
  119. done(map[string]int{"featureVersion": protocol.FeatureVersion}, nil)
  120. return
  121. }
  122. if method == "page.new" {
  123. if len(h.pages) >= 16 {
  124. done(nil, api.Err("BROWSER_LIMIT", "native page quota reached"))
  125. return
  126. }
  127. h.next++
  128. id := h.next
  129. h.pages[id] = true
  130. h.backend.NewPage(id, func(err error) {
  131. if err != nil {
  132. delete(h.pages, id)
  133. done(nil, err)
  134. return
  135. }
  136. if ctx.Err() != nil {
  137. _ = h.backend.ClosePage(id)
  138. delete(h.pages, id)
  139. done(nil, ctx.Err())
  140. return
  141. }
  142. done(id, nil)
  143. })
  144. return
  145. }
  146. if method != "page.navigate" && method != "page.evaluate" && method != "page.close" && method != "page.capture" && method != "page.input" {
  147. done(nil, api.Err("BROWSER_CAPABILITY_UNSUPPORTED", "unknown native worker method"))
  148. return
  149. }
  150. if !h.pages[args.Page] {
  151. done(nil, api.Err("BROWSER_PAGE_NOT_FOUND", "native page is unavailable"))
  152. return
  153. }
  154. switch method {
  155. case "page.capture", "page.input":
  156. if h.evaluations >= 32 {
  157. done(nil, api.Err("BROWSER_LIMIT", "too many native operations pending"))
  158. return
  159. }
  160. complete := h.track(args.Page, done)
  161. if method == "page.input" {
  162. backend, ok := h.backend.(inputBackend)
  163. if !ok {
  164. complete(nil, api.Err("BROWSER_CAPABILITY_UNSUPPORTED", "native trusted input is unavailable"))
  165. return
  166. }
  167. backend.Input(args.Page, args.Action, args.Value, args.X, args.Y, func(err error) { complete(true, err) })
  168. } else {
  169. backend, ok := h.backend.(captureBackend)
  170. if !ok {
  171. complete(nil, api.Err("BROWSER_CAPABILITY_UNSUPPORTED", "native capture is unavailable"))
  172. return
  173. }
  174. captureCompleted := false
  175. backend.Capture(args.Page, args.FullPage, func(data []byte, err error) {
  176. if captureCompleted {
  177. return
  178. }
  179. captureCompleted = true
  180. if ctx.Err() != nil {
  181. complete(nil, ctx.Err())
  182. return
  183. }
  184. if !h.pages[args.Page] {
  185. complete(nil, api.Err("BROWSER_CLOSED", "page closed during capture"))
  186. return
  187. }
  188. var name string
  189. if err == nil {
  190. name, err = capture.Save(h.options.DownloadDir, data)
  191. }
  192. complete(name, err)
  193. })
  194. }
  195. case "page.close":
  196. delete(h.pages, args.Page)
  197. h.cancelEvaluations(args.Page)
  198. done(true, h.backend.ClosePage(args.Page))
  199. case "page.navigate":
  200. if strings.ContainsRune(args.URL, 0) {
  201. done(nil, api.Err("BROWSER_INVALID_ARGUMENT", "URL contains NUL"))
  202. return
  203. }
  204. if args.Op != "goto" && args.Op != "back" && args.Op != "forward" && args.Op != "reload" {
  205. done(nil, api.Err("BROWSER_INVALID_ARGUMENT", "invalid navigation operation"))
  206. return
  207. }
  208. h.backend.Navigate(args.Page, args.URL, args.Op, func(url string, err error) { done(url, err) })
  209. case "page.evaluate":
  210. if strings.ContainsRune(args.Script, 0) {
  211. done(nil, api.Err("BROWSER_INVALID_ARGUMENT", "script contains NUL"))
  212. return
  213. }
  214. if len(args.Script) > protocol.MaxMessage/2 {
  215. done(nil, api.Err("BROWSER_ARGUMENT_LIMIT", "script exceeds worker limit"))
  216. return
  217. }
  218. if h.evaluations >= 32 {
  219. done(nil, api.Err("BROWSER_LIMIT", "too many native evaluations pending"))
  220. return
  221. }
  222. h.evaluations++
  223. h.nextEvaluation++
  224. evaluation := h.nextEvaluation
  225. if h.pending[args.Page] == nil {
  226. h.pending[args.Page] = map[uint64]func(){}
  227. }
  228. finished := false
  229. complete := func(value json.RawMessage, err error) {
  230. if finished {
  231. return
  232. }
  233. finished = true
  234. h.evaluations--
  235. delete(h.pending[args.Page], evaluation)
  236. if len(h.pending[args.Page]) == 0 {
  237. delete(h.pending, args.Page)
  238. }
  239. if err == nil && (len(value) > protocol.MaxMessage-1024 || !json.Valid(value)) {
  240. err = api.Err("BROWSER_INVALID_RESULT", "native evaluation did not return bounded JSON")
  241. }
  242. done(value, err)
  243. }
  244. h.pending[args.Page][evaluation] = func() { complete(nil, api.Err("BROWSER_CLOSED", "page closed during evaluation")) }
  245. h.backend.Evaluate(args.Page, args.Script, complete)
  246. }
  247. })
  248. }
  249. // Close is called on the UI thread after protocol handlers have been canceled.
  250. func (h *Host) Close() {
  251. for page := range h.pending {
  252. h.cancelEvaluations(page)
  253. }
  254. h.pages = map[uint64]bool{}
  255. h.backend.Close()
  256. }
  257. func (h *Host) cancelEvaluations(page uint64) {
  258. for _, cancel := range h.pending[page] {
  259. cancel()
  260. }
  261. }
  262. func (h *Host) track(page uint64, done func(any, error)) func(any, error) {
  263. h.evaluations++
  264. h.nextEvaluation++
  265. id := h.nextEvaluation
  266. if h.pending[page] == nil {
  267. h.pending[page] = map[uint64]func(){}
  268. }
  269. finished := false
  270. complete := func(v any, e error) {
  271. if finished {
  272. return
  273. }
  274. finished = true
  275. h.evaluations--
  276. delete(h.pending[page], id)
  277. if len(h.pending[page]) == 0 {
  278. delete(h.pending, page)
  279. }
  280. done(v, e)
  281. }
  282. h.pending[page][id] = func() { complete(nil, api.Err("BROWSER_CLOSED", "page closed during operation")) }
  283. return complete
  284. }