gnunet-handbook

The GNUnet Handbook
Log | Files | Refs

websocket.py (7960B)


      1 """The WebSocket domain for documenting bidirectional connections."""
      2 
      3 from dataclasses import dataclass
      4 from hashlib import sha256
      5 
      6 from docutils import nodes
      7 
      8 from sphinx import addnodes
      9 from sphinx.directives import ObjectDescription, directives
     10 from sphinx.domains import Domain, Index, ObjType
     11 from sphinx.locale import get_translation
     12 from sphinx.roles import XRefRole
     13 from sphinx.util import logging
     14 from sphinx.util.docfields import GroupedField, TypedField
     15 from sphinx.util.nodes import make_refnode
     16 
     17 from ._path_signature import render_path_signature
     18 
     19 
     20 _ = get_translation('httpdomain')
     21 logger = logging.getLogger(__name__)
     22 
     23 
     24 @dataclass(frozen=True)
     25 class ConnectionRecord:
     26     """The persisted, indexed data for one WebSocket connection."""
     27 
     28     docname: str
     29     synopsis: str
     30     deprecated: bool
     31 
     32 
     33 def connection_anchor(raw_signature):
     34     """Return the stable anchor for an indexed WebSocket connection."""
     35     slug = nodes.make_id(raw_signature) or 'connection'
     36     digest = sha256(raw_signature.encode('utf-8')).hexdigest()
     37     return 'websocket-%s-%s' % (slug, digest)
     38 
     39 
     40 class WebSocketConnection(ObjectDescription):
     41     """Describe a WebSocket connection at an application path."""
     42 
     43     doc_field_types = [
     44         TypedField('parameter', label=_('Parameters'), names=('param',)),
     45         TypedField('queryparameter', label=_('Query Parameters'), names=('query',)),
     46         GroupedField('servermessage', label=_('Messages sent by server'),
     47                      names=('server-message',)),
     48         GroupedField('clientmessage', label=_('Messages sent by client'),
     49                      names=('client-message',)),
     50     ]
     51 
     52     option_spec = {
     53         'deprecated': directives.flag,
     54         'noindex': directives.flag,
     55         'no-index': directives.flag,
     56         'addtoc': directives.flag,
     57         'synopsis': lambda value: value,
     58     }
     59 
     60     def run(self):
     61         # Sphinx 6 only recognizes ``noindex``.  Sphinx 9 accepts both names,
     62         # but normalizing here keeps the documented spelling cross-version.
     63         if 'no-index' in self.options:
     64             self.options['noindex'] = self.options.pop('no-index')
     65         return super().run()
     66 
     67     def handle_signature(self, sig, signode):
     68         if not sig.startswith('/'):
     69             _, line = self.get_source_info()
     70             logger.warning(
     71                 'WebSocket connection paths must begin with "/": %s', sig,
     72                 location=(self.env.docname, line),
     73             )
     74             raise ValueError
     75 
     76         prefix = 'WebSocket '
     77         signode += addnodes.desc_name(prefix, prefix)
     78         render_path_signature(sig, signode)
     79         signode['path'] = sig
     80         signode['fullname'] = prefix + sig
     81         return sig
     82 
     83     def needs_arglist(self):
     84         return False
     85 
     86     def add_target_and_index(self, name, sig, signode):
     87         connections = self.env.domaindata['websocket']['connections']
     88         record = ConnectionRecord(
     89             self.env.docname,
     90             self.options.get('synopsis', ''),
     91             'deprecated' in self.options,
     92         )
     93         previous = connections.get(sig)
     94         if previous is not None:
     95             _, line = self.get_source_info()
     96             logger.warning(
     97                 'duplicate WebSocket connection definition %s in %s; '
     98                 'existing definition is in %s. Use :noindex: for an '
     99                 'intentional secondary rendering.',
    100                 sig,
    101                 self.env.doc2path(self.env.docname),
    102                 self.env.doc2path(previous.docname),
    103                 location=(self.env.docname, line),
    104             )
    105             return
    106         signode['ids'].append(connection_anchor(sig))
    107         connections[sig] = record
    108 
    109     def get_index_text(self, modname, name):
    110         return ''
    111 
    112     def _object_hierarchy_parts(self, sig_node):
    113         if ('addtoc' not in self.options or 'noindex' in self.options or
    114                 'no-index' in self.options):
    115             return ()
    116         path = sig_node.get('path')
    117         if not path:
    118             return ()
    119         return tuple(part for part in path.split('/') if part) + (
    120             'WebSocket ' + path,
    121         )
    122 
    123     def _toc_entry_name(self, sig_node):
    124         if not sig_node.get('_toc_parts'):
    125             return ''
    126         return sig_node['_toc_parts'][-1]
    127 
    128 
    129 class WebSocketXRefRole(XRefRole):
    130     """Cross-reference a WebSocket connection."""
    131 
    132     def process_link(self, env, refnode, has_explicit_title, title, target):
    133         if not has_explicit_title:
    134             title = 'WebSocket ' + title
    135         return title, target
    136 
    137 
    138 class WebSocketIndex(Index):
    139     """Generated index of indexed WebSocket connections."""
    140 
    141     name = 'routingtable'
    142     localname = _('WebSocket Routing Table')
    143     shortname = _('WebSocket routing table')
    144 
    145     @staticmethod
    146     def grouping_prefix(path):
    147         parts = [part for part in path.split('/') if part]
    148         return '/%s' % (parts[0] if parts else '')
    149 
    150     def generate(self, docnames=None):
    151         content = {}
    152         for path, record in sorted(self.domain.connections.items()):
    153             entries = content.setdefault(self.grouping_prefix(path), [])
    154             entries.append([
    155                 'WebSocket ' + path,
    156                 0,
    157                 record.docname,
    158                 connection_anchor(path),
    159                 '',
    160                 _('Deprecated') if record.deprecated else '',
    161                 record.synopsis,
    162             ])
    163         return sorted(content.items()), True
    164 
    165 
    166 class WebSocketDomain(Domain):
    167     """WebSocket documentation domain."""
    168 
    169     name = 'websocket'
    170     label = 'WebSocket'
    171     data_version = 1
    172 
    173     object_types = {
    174         'connection': ObjType('connection', 'connection'),
    175     }
    176     directives = {
    177         'connection': WebSocketConnection,
    178     }
    179     roles = {
    180         'connection': WebSocketXRefRole(),
    181     }
    182     initial_data = {
    183         'connections': {},
    184     }
    185     indices = [WebSocketIndex]
    186 
    187     @property
    188     def connections(self):
    189         return self.data['connections']
    190 
    191     def clear_doc(self, docname):
    192         for signature, record in list(self.connections.items()):
    193             if record.docname == docname:
    194                 del self.connections[signature]
    195 
    196     def resolve_xref(self, env, fromdocname, builder, typ, target,
    197                      node, contnode):
    198         if not target.startswith('/'):
    199             logger.warning(
    200                 'WebSocket connection targets must begin with "/": %s',
    201                 target,
    202                 location=node,
    203             )
    204             return contnode
    205 
    206         record = self.connections.get(target)
    207         if record is None:
    208             return contnode
    209         return make_refnode(
    210             builder,
    211             fromdocname,
    212             record.docname,
    213             connection_anchor(target),
    214             contnode,
    215             'WebSocket ' + target,
    216         )
    217 
    218     def resolve_any_xref(self, env, fromdocname, builder, target, node,
    219                          contnode):
    220         return []
    221 
    222     def get_objects(self):
    223         for signature, record in self.connections.items():
    224             yield (
    225                 signature,
    226                 signature,
    227                 'connection',
    228                 record.docname,
    229                 connection_anchor(signature),
    230                 1,
    231             )
    232 
    233     def merge_domaindata(self, docnames, otherdata):
    234         for signature, record in otherdata['connections'].items():
    235             previous = self.connections.get(signature)
    236             if previous is not None and previous != record:
    237                 logger.warning(
    238                     'duplicate WebSocket connection definition %s in %s; '
    239                     'existing definition is in %s. Use :noindex: for an '
    240                     'intentional secondary rendering.',
    241                     signature,
    242                     self.env.doc2path(record.docname),
    243                     self.env.doc2path(previous.docname),
    244                 )
    245                 continue
    246             self.connections[signature] = record