4:2
  B   ˆl–äY>”JeJe@†à¸Û*bÑ¿�þDãñ¬Ü¡p¬ˆ$‘¦�üÿÂƒ}ç™Á_ŠI|¥�+Wé3ž¯ÁÀ &›    # Infinite push
#
# Copyright 2016 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.


import logging
import os
import time

import warnings
import mysql.connector

from . import indexapi


def _convertbookmarkpattern(pattern):
    pattern = pattern.replace(b'_', b'\\_')
    pattern = pattern.replace(b'%', b'\\%')
    if pattern.endswith(b'*'):
        pattern = pattern[:-1] + b'%'
    return pattern


class sqlindexapi(indexapi.indexapi):
    """
    Sql backend for infinitepush index. See schema.sql
    """

    def __init__(
        self,
        reponame,
        host,
        port,
        database,
        user,
        password,
        logfile,
        loglevel,
        waittimeout=300,
        locktimeout=120,
    ):
        super(sqlindexapi, self).__init__()
        self.reponame = reponame
        self.sqlargs = {
            b'host': host,
            b'port': port,
            b'database': database,
            b'user': user,
            b'password': password,
        }
        self.sqlconn = None
        self.sqlcursor = None
        if not logfile:
            logfile = os.devnull
        logging.basicConfig(filename=logfile)
        self.log = logging.getLogger()
        self.log.setLevel(loglevel)
        self._connected = False
        self._waittimeout = waittimeout
        self._locktimeout = locktimeout

    def sqlconnect(self):
        if self.sqlconn:
            raise indexapi.indexexception(b"SQL connection already open")
        if self.sqlcursor:
            raise indexapi.indexexception(
                b"SQL cursor already open without connection"
            )
        retry = 3
        while True:
            try:
                self.sqlconn = mysql.connector.connect(**self.sqlargs)

                # Code is copy-pasted from hgsql. Bug fixes need to be
                # back-ported!
                # The default behavior is to return byte arrays, when we
                # need strings. This custom convert returns strings.
                self.sqlconn.set_converter_class(CustomConverter)
                self.sqlconn.autocommit = False
                break
            except mysql.connector.errors.Error:
                # mysql can be flakey occasionally, so do some minimal
                # retrying.
                retry -= 1
                if retry == 0:
                    raise
                time.sleep(0.2)

        waittimeout = self.sqlconn.converter.escape(b'%s' % self._waittimeout)

        self.sqlcursor = self.sqlconn.cursor()
        self.sqlcursor.execute(b"SET wait_timeout=%s" % waittimeout)
        self.sqlcursor.execute(
            b"SET innodb_lock_wait_timeout=%s" % self._locktimeout
        )
        self._connected = True

    def close(self):
        """Cleans up the metadata store connection."""
        with warnings.catch_warnings():
            warnings.simplefilter(b"ignore")
            self.sqlcursor.close()
            self.sqlconn.close()
        self.sqlcursor = None
        self.sqlconn = None

    def __enter__(self):
        if not self._connected:
            self.sqlconnect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            self.sqlconn.commit()
        else:
            self.sqlconn.rollback()

    def addbundle(self, bundleid, nodesctx):
        if not self._connected:
            self.sqlconnect()
        self.log.info(b"ADD BUNDLE %r %r" % (self.reponame, bundleid))
        self.sqlcursor.execute(
            b"INSERT INTO bundles(bundle, reponame) VALUES (%s, %s)",
            params=(bundleid, self.reponame),
        )
        for ctx in nodesctx:
            self.sqlcursor.execute(
                b"INSERT INTO nodestobundle(node, bundle, reponame) "
                b"VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE "
                b"bundle=VALUES(bundle)",
                params=(ctx.hex(), bundl