<commit_before># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itertools
import uuid

from functools import partial
from typing import Optional

import arrow
import cattr
import tenacity
import trio

from linehaul.events import parser as _event_parser
from linehaul.protocol import LineReceiver
from linehaul.syslog import parser as _syslog_parser


retry = partial(tenacity.retry, sleep=trio.sleep)


_cattr = cattr.Converter()
_cattr.register_unstructure_hook(arrow.Arrow, lambda o: o.float_timestamp)


#
# Non I/O Functions
#


def parse_line(line: bytes, token=None) -> Optional[_event_parser.Download]:
    line = line.decode("utf8")

    # Check our token, and remove it from the start of the line if it matches.
    if token is not None:
        # TODO: Use a Constant Time Compare?
        if not line.startswith(token):
            return
        line = line[len(token) :]

    # Parse the incoming Syslog Message, and get the download event out of it.
    try:
        msg = _syslog_parser.parse(line)
        event = _event_parser.parse(msg.message)
    except ValueError:
        # TODO: Better Error Logging.
        return

    return event


def extract_item_date(item):
    return item.timestamp.format("YYYYMDDD")


def compute_batches(all_items):
    for date, items in itertools.groupby(
        sorted(all_items, key=extract_item_date), extract_item_date
    ):
        items = list(items)

        yield extract_item_date(items[0]), [
            {"insertId": str(uuid.uuid4()), "json": row}
            for row in _cattr.unstructure(items[:1])
        ],


#
# I/O Functions
#


async def handle_connection(stream, q, token=None):
    lr = LineReceiver(partial(parse_line, token=token))

    while True:
        try:
            data: bytes = await stream.receive_some(1024)
        except trio.BrokenStreamError:
            data = b""<commit_msg>Remove a bit of debug code<commit_after># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import itertools
import uuid

from functools import partial
from typing import Optional

import arrow
import cattr
import tenacity
import trio

from linehaul.events import parser as _event_parser
from linehaul.protocol import LineReceiver
from linehaul.syslog import parser as _syslog_parser


retry = partial(tenacity.retry, sleep=trio.sleep)


_cattr = cattr.Converter()
_cattr.register_unstructure_hook(arrow.Arrow, lambda o: o.float_timestamp)


#
# Non I/O Functions
#


def parse_line(line: bytes, token=None) -> Optional[_event_parser.Download]:
    line = line.decode("utf8")

    # Check our token, and remove it from the start of the line if it matches.
    if token is not None:
        # TODO: Use a Constant Time Compare?
        if not line.startswith(token):
            return
        line = line[len(token) :]

    # Parse the incoming Syslog Message, and get the download event out of it.
    try:
        msg = _syslog_parser.parse(line)
        event = _event_parser.parse(msg.message)
    except ValueError:
        # TODO: Better Error Logging.
        return

    return event


def extract_item_date(item):
    return item.timestamp.format("YYYYMDDD")


def compute_batches(all_items):
    for date, items in itertools.groupby(
        sorted(all_items, key=extract_item_date), extract_item_date
    ):
        items = list(items)

        yield extract_item_date(items[0]), [
            {"insertId": str(uuid.uuid4()), "json": row}
            for row in _cattr.unstructure(items)
        ],


#
# I/O Functions
#


async def handle_connection(stream, q, token=None):
    lr = LineReceiver(partial(parse_line, token=token))

    while True:
        try:
            data: bytes = await stream.receive_some(1024)
        except trio.BrokenStreamError:
            data = b""
{'fraction_non_alphanumeric': 0.081877499473795, 'fraction_numerical': 0.00484108608713955, 'mean_word_length': 3.288808664259928, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '306157', 'n_tokens_mistral': 1394, 'n_tokens_neox': 1353, 'n_words': 484}