Debian Codegraph @

hgext/fastannotate/protocol.py

raw
1 # Copyright 2016-present Facebook. All Rights Reserved.
2 #
3 # protocol: logic for a server providing fastannotate support
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7 from __future__ import annotations
8
9 import contextlib
10 import os
11
12 from mercurial.i18n import _
13 from mercurial import (
14 error,
15 extensions,
16 hg,
17 util,
18 wireprotov1peer,
19 wireprotov1server,
20 )
21 from mercurial.repo import (
22 factory as repo_factory,
23 )
24 from mercurial.utils import (
25 urlutil,
26 )
27 from . import context
28
29 # common
30
31
32 def _getmaster(ui):
33 """get the mainbranch, and enforce it is set"""
34 master = ui.config(b'fastannotate', b'mainbranch')
35 if not master:
36 raise error.Abort(
37 _(
38 b'fastannotate.mainbranch is required '
39 b'for both the client and the server'
40 )
41 )
42 return master
43
44
45 # server-side
46
47
48 def _capabilities(orig, repo, proto):
49 result = orig(repo, proto)
50 result.append(b'getannotate')
51 return result
52
53
54 def _getannotate(repo, proto, path, lastnode):
55 # output:
56 # FILE := vfspath + '\0' + str(size) + '\0' + content
57 # OUTPUT := '' | FILE + OUTPUT
58 result = b''
59 buildondemand = repo.ui.configbool(
60 b'fastannotate', b'serverbuildondemand', True
61 )
62 with context.annotatecontext(repo, path) as actx:
63 if buildondemand:
64 # update before responding to the client
65 master = _getmaster(repo.ui)
66 try:
67 if not actx.isuptodate(master):
68 actx.annotate(master, master)
69 except Exception:
70 # non-fast-forward move or corrupted. rebuild automically.
71 actx.rebuild()
72 try:
73 actx.annotate(master, master)
74 except Exception:
75 actx.rebuild() # delete files
76 finally:
77 # although the "with" context will also do a close/flush, we
78 # need to do it early so we can send the correct respond to
79 # client.
80 actx.close()
81 # send back the full content of revmap and linelog, in the future we
82 # may want to do some rsync-like fancy updating.
83 # the lastnode check is not necessary if the client and the server
84 # agree where the main branch is.
85 if actx.lastnode != lastnode:
86 for p in [actx.revmappath, actx.linelogpath]:
87 if not os.path.exists(p):
88 continue
89 with open(p, 'rb') as f:
90 content = f.read()
91 vfsbaselen = len(repo.vfs.base + b'/')
92 relpath = p[vfsbaselen:]
93 result += b'%s\0%d\0%s' % (relpath, len(content), content)
94 return result
95
96
97 def _registerwireprotocommand():
98 if b'getannotate' in wireprotov1server.commands:
99 return
100 wireprotov1server.wireprotocommand(b'getannotate', b'path lastnode')(
101 _getannotate
102 )
103
104
105 def serveruisetup(ui):
106 _registerwireprotocommand()
107 extensions.wrapfunction(wireprotov1server, '_capabilities', _capabilities)
108
109
110 # client-side
111
112
113 def _parseresponse(payload):
114 result = {}
115 i = 0
116 l = len(payload) - 1
117 state = 0 # 0: vfspath, 1: size
118 vfspath = size = b''
119 while i < l:
120 ch = payload[i : i + 1]
121 if ch == b'\0':
122 if state == 1:
123 result[vfspath] = payload[i + 1 : i + 1 + int(size)]
124 i += int(size)
125 state = 0
126 vfspath = size = b''
127 elif state == 0:
128 state = 1
129 else:
130 if state == 1:
131 size += ch
132 elif state == 0:
133 vfspath += ch
134 i += 1
135 return result
136
137
138 def peersetup(ui, peer):
139 class fastannotatepeer(peer.__class__):
140 @wireprotov1peer.batchable
141 def getannotate(self, path, lastnode=None):
142 if not self.capable(b'getannotate'):
143 ui.warn(_(b'remote peer cannot provide annotate cache\n'))
144 return None, None
145 else:
146 args = {b'path': path, b'lastnode': lastnode or b''}
147 return args, _parseresponse
148
149 peer.__class__ = fastannotatepeer
150
151
152 @contextlib.contextmanager
153 def annotatepeer(repo):
154 ui = repo.ui
155
156 remotedest = ui.config(b'fastannotate', b'remotepath', b'default')
157 remotepath = urlutil.get_unique_pull_path_obj(
158 b'fastannotate',
159 ui,
160 remotedest,
161 )
162 peer = repo_factory.peer(ui, {}, remotepath)
163
164 try:
165 yield peer
166 finally:
167 peer.close()
168
169
170 def clientfetch(repo, paths, lastnodemap=None, peer=None):
171 """download annotate cache from the server for paths"""
172 if not paths:
173 return
174
175 if peer is None:
176 with annotatepeer(repo) as peer:
177 return clientfetch(repo, paths, lastnodemap, peer)
178
179 if lastnodemap is None:
180 lastnodemap = {}
181
182 ui = repo.ui
183 results = []
184 with peer.commandexecutor() as batcher:
185 ui.debug(b'fastannotate: requesting %d files\n' % len(paths))
186 for p in paths:
187 results.append(
188 batcher.callcommand(
189 b'getannotate',
190 {b'path': p, b'lastnode': lastnodemap.get(p)},
191 )
192 )
193
194 for result in results:
195 r = result.result()
196 # TODO: pconvert these paths on the server?
197 r = {util.pconvert(p): v for p, v in r.items()}
198 for path in sorted(r):
199 # ignore malicious paths
200 if not path.startswith(b'fastannotate/') or b'/../' in (
201 path + b'/'
202 ):
203 ui.debug(
204 b'fastannotate: ignored malicious path %s\n' % path
205 )
206 continue
207 content = r[path]
208 if ui.debugflag:
209 ui.debug(
210 b'fastannotate: writing %d bytes to %s\n'
211 % (len(content), path)
212 )
213 repo.vfs.makedirs(os.path.dirname(path))
214 with repo.vfs(path, b'wb') as f:
215 f.write(content)
216
217
218 def _filterfetchpaths(repo, paths):
219 """return a subset of paths whose history is long and need to fetch linelog
220 from the server. works with remotefilelog and non-remotefilelog repos.
221 """
222 threshold = repo.ui.configint(b'fastannotate', b'clientfetchthreshold', 10)
223 if threshold <= 0:
224 return paths
225
226 result = []
227 for path in paths:
228 try:
229 if len(repo.file(path)) >= threshold:
230 result.append(path)
231 except Exception: # file not found etc.
232 result.append(path)
233
234 return result
235
236
237 def localreposetup(ui, repo):
238 class fastannotaterepo(repo.__class__):
239 def prefetchfastannotate(self, paths, peer=None):
240 master = _getmaster(self.ui)
241 needupdatepaths = []
242 lastnodemap = {}
243 try:
244 for path in _filterfetchpaths(self, paths):
245 with context.annotatecontext(self, path) as actx:
246 if not actx.isuptodate(master, strict=False):
247 needupdatepaths.append(path)
248 lastnodemap[path] = actx.lastnode
249 if needupdatepaths:
250 clientfetch(self, needupdatepaths, lastnodemap, peer)
251 except Exception as ex:
252 # could be directory not writable or so, not fatal
253 self.ui.debug(b'fastannotate: prefetch failed: %r\n' % ex)
254
255 repo.__class__ = fastannotaterepo
256
257
258 def clientreposetup(ui, repo):
259 _registerwireprotocommand()
260 if repo.local():
261 localreposetup(ui, repo)
262 # TODO: this mutates global state, but only if at least one repo
263 # has the extension enabled. This is probably bad for hgweb.
264 if peersetup not in hg.wirepeersetupfuncs:
265 hg.wirepeersetupfuncs.append(peersetup)