ClsiCookieManager.mjs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import { URL, URLSearchParams } from 'node:url'
  2. import OError from '@overleaf/o-error'
  3. import Settings from '@overleaf/settings'
  4. import {
  5. fetchNothing,
  6. fetchStringWithResponse,
  7. RequestFailedError,
  8. } from '@overleaf/fetch-utils'
  9. import RedisWrapper from '../../infrastructure/RedisWrapper.mjs'
  10. import Cookie from 'cookie'
  11. import logger from '@overleaf/logger'
  12. import Metrics from '@overleaf/metrics'
  13. const clsiCookiesEnabled = (Settings.clsiCookie?.key ?? '') !== ''
  14. const rclient = RedisWrapper.client('clsi_cookie')
  15. let rclientSecondary
  16. if (Settings.redis.clsi_cookie_secondary != null) {
  17. rclientSecondary = RedisWrapper.client('clsi_cookie_secondary')
  18. }
  19. const ClsiCookieManagerFactory = function (backendGroup) {
  20. /**
  21. * @param {string} projectId
  22. * @param {string | null} userId
  23. * @param {string} compileBackendClass
  24. * @return {string}
  25. */
  26. function buildKey(projectId, userId, compileBackendClass) {
  27. if (backendGroup != null) {
  28. return `clsiserver:${backendGroup}:${compileBackendClass}:${projectId}:${userId}`
  29. } else {
  30. return `clsiserver:${compileBackendClass}:${projectId}:${userId}`
  31. }
  32. }
  33. async function getServerId(
  34. projectId,
  35. userId,
  36. compileGroup,
  37. compileBackendClass
  38. ) {
  39. if (!clsiCookiesEnabled) {
  40. return
  41. }
  42. const serverId = await rclient.get(
  43. buildKey(projectId, userId, compileBackendClass)
  44. )
  45. if (!serverId) {
  46. return await cookieManager.promises._populateServerIdViaRequest(
  47. projectId,
  48. userId,
  49. compileGroup,
  50. compileBackendClass
  51. )
  52. } else {
  53. return serverId
  54. }
  55. }
  56. async function _populateServerIdViaRequest(
  57. projectId,
  58. userId,
  59. compileGroup,
  60. compileBackendClass
  61. ) {
  62. const u = new URL(`${Settings.apis.clsi.url}/project/${projectId}/status`)
  63. u.search = new URLSearchParams({
  64. compileGroup,
  65. compileBackendClass,
  66. }).toString()
  67. let res
  68. try {
  69. res = await fetchNothing(u.href, {
  70. method: 'POST',
  71. signal: AbortSignal.timeout(30_000),
  72. })
  73. } catch (err) {
  74. OError.tag(err, 'error getting initial server id for project', {
  75. project_id: projectId,
  76. })
  77. throw err
  78. }
  79. if (!clsiCookiesEnabled) {
  80. return
  81. }
  82. const serverId = cookieManager._parseServerIdFromResponse(res)
  83. try {
  84. await cookieManager.promises.setServerId(
  85. projectId,
  86. userId,
  87. compileGroup,
  88. compileBackendClass,
  89. serverId,
  90. null
  91. )
  92. return serverId
  93. } catch (err) {
  94. logger.warn(
  95. { err, projectId },
  96. 'error setting server id via populate request'
  97. )
  98. throw err
  99. }
  100. }
  101. function _parseServerIdFromResponse(response) {
  102. const cookies = Cookie.parse(response.headers['set-cookie']?.[0] || '')
  103. return cookies?.[Settings.clsiCookie.key]
  104. }
  105. async function checkIsLoadSheddingEvent(
  106. clsiserverid,
  107. compileGroup,
  108. compileBackendClass
  109. ) {
  110. let status
  111. try {
  112. const params = new URLSearchParams({
  113. clsiserverid,
  114. compileGroup,
  115. compileBackendClass,
  116. }).toString()
  117. const { response, body } = await fetchStringWithResponse(
  118. `${Settings.apis.clsi.url}/instance-state?${params}`,
  119. {
  120. method: 'GET',
  121. signal: AbortSignal.timeout(30_000),
  122. }
  123. )
  124. status =
  125. response.status === 200 && body === `${clsiserverid},UP\n`
  126. ? 'load-shedding'
  127. : 'cycle'
  128. } catch (err) {
  129. if (err instanceof RequestFailedError && err.response.status === 404) {
  130. status = 'cycle'
  131. } else {
  132. status = 'error'
  133. logger.warn({ err, clsiserverid }, 'cannot probe clsi VM')
  134. }
  135. }
  136. Metrics.inc('clsi-lb-switch-backend', 1, { status })
  137. }
  138. function _getTTLInSeconds(clsiServerId) {
  139. return (clsiServerId || '').includes('-reg-')
  140. ? Settings.clsiCookie.ttlInSecondsRegular
  141. : Settings.clsiCookie.ttlInSeconds
  142. }
  143. async function setServerId(
  144. projectId,
  145. userId,
  146. compileGroup,
  147. compileBackendClass,
  148. serverId,
  149. previous
  150. ) {
  151. if (!clsiCookiesEnabled) {
  152. return
  153. }
  154. if (serverId == null) {
  155. // We don't get a cookie back if it hasn't changed
  156. return await rclient.expire(
  157. buildKey(projectId, userId, compileBackendClass),
  158. _getTTLInSeconds(previous)
  159. )
  160. }
  161. if (!previous) {
  162. // Initial assignment of a user+project or after clearing cache.
  163. Metrics.inc('clsi-lb-assign-initial-backend')
  164. } else {
  165. await checkIsLoadSheddingEvent(
  166. previous,
  167. compileGroup,
  168. compileBackendClass
  169. )
  170. }
  171. if (rclientSecondary != null) {
  172. await _setServerIdInRedis(
  173. rclientSecondary,
  174. projectId,
  175. userId,
  176. compileBackendClass,
  177. serverId
  178. ).catch(() => {})
  179. }
  180. await _setServerIdInRedis(
  181. rclient,
  182. projectId,
  183. userId,
  184. compileBackendClass,
  185. serverId
  186. )
  187. }
  188. async function _setServerIdInRedis(
  189. rclient,
  190. projectId,
  191. userId,
  192. compileBackendClass,
  193. serverId
  194. ) {
  195. await rclient.setex(
  196. buildKey(projectId, userId, compileBackendClass),
  197. _getTTLInSeconds(serverId),
  198. serverId
  199. )
  200. }
  201. async function clearServerId(projectId, userId, compileBackendClass) {
  202. if (!clsiCookiesEnabled) {
  203. return
  204. }
  205. try {
  206. await rclient.del(buildKey(projectId, userId, compileBackendClass))
  207. } catch (err) {
  208. // redis errors need wrapping as the instance may be shared
  209. throw new OError(
  210. 'Failed to clear clsi persistence',
  211. { projectId, userId },
  212. err
  213. )
  214. }
  215. }
  216. const cookieManager = {
  217. _parseServerIdFromResponse,
  218. promises: {
  219. getServerId,
  220. clearServerId,
  221. _populateServerIdViaRequest,
  222. setServerId,
  223. },
  224. }
  225. return cookieManager
  226. }
  227. export default ClsiCookieManagerFactory