<commit_before># Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>

from ggrc import db, settings
from ggrc.login import get_current_user
from .mixins import deferred, Base, Stateful
from functools import wraps
from flask import request
from flask.wrappers import Response
from ggrc.models.types import CompressedType
from time import time


class BackgroundTask(Base, Stateful, db.Model):
  __tablename__ = 'background_tasks'

  VALID_STATES = [
      "Pending",
      "Running",
      "Success",
      "Failure"
  ]
  name = deferred(db.Column(db.String), 'BackgroundTask')
  parameters = deferred(db.Column(CompressedType), 'BackgroundTask')
  result = deferred(db.Column(CompressedType), 'BackgroundTask')

  _publish_attrs = [
      'name',
      'result'
  ]

  def start(self):
    self.status = "Running"
    db.session.add(self)
    db.session.commit()

  def finish(self, status, result):
    # Ensure to not commit any not-yet-committed changes
    db.session.rollback()

    if isinstance(result, Response):
      self.result = {'content': result.response[0],
                     'status_code': result.status_code,
                     'headers': result.headers.items()}
    else:
      self.result = {'content': result,
                     'status_code': 200,
                     'headers': [('Content-Type', 'text/html')]}
    self.status = status
    db.session.add(self)
    db.session.commit()

  def make_response(self, default=None):
    if self.result is None:
      return default
    from ggrc.app import app
    return app.make_response((self.result['content'],
                              self.result['status_code'],
                              self.result['headers']))


def create_task(name, url, queued_task=None, parameters={}):

  # task name must be unique
  task = BackgroundTask(name=name + str(int(time())))
  task.parameters = parameters
  task.modified_by = get_current_user()
  db.session.add(task)
  db.session.commit()

  # schedule a task queue
  if getattr(settings, 'APP_ENGINE', False):
    from google.appengine.api import taskqueue
    if request.method == "POST":
      headers = [h for h in request.headers if h[0] == 'Cookie']
    else:
      headers = request.headers
    taskqueue.add(
        queue_name="ggrc",
        url=url,
        name=task.name,
        params={'task_id': task.id},
        method=request.method,
        headers=headers)
  elif queued_task:
    queued_task(task)
  return task


def make_task_response(id):
  task = BackgroundTask.query.get(id)
  return task.make_response()


def queued_task(func):
  from ggrc.app import app

  @wraps(func)
  def decorated_view(*args, **kwargs):
    if len(args) > 0 and isinstance(args[0], BackgroundTask):
      task = args[0]<commit_msg>CORE-614 Make AE background task names unique<commit_after># Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>

from ggrc import db, settings
from ggrc.login import get_current_user
from .mixins import deferred, Base, Stateful
from functools import wraps
from flask import request
from flask.wrappers import Response
from ggrc.models.types import CompressedType
from time import time


class BackgroundTask(Base, Stateful, db.Model):
  __tablename__ = 'background_tasks'

  VALID_STATES = [
      "Pending",
      "Running",
      "Success",
      "Failure"
  ]
  name = deferred(db.Column(db.String), 'BackgroundTask')
  parameters = deferred(db.Column(CompressedType), 'BackgroundTask')
  result = deferred(db.Column(CompressedType), 'BackgroundTask')

  _publish_attrs = [
      'name',
      'result'
  ]

  def start(self):
    self.status = "Running"
    db.session.add(self)
    db.session.commit()

  def finish(self, status, result):
    # Ensure to not commit any not-yet-committed changes
    db.session.rollback()

    if isinstance(result, Response):
      self.result = {'content': result.response[0],
                     'status_code': result.status_code,
                     'headers': result.headers.items()}
    else:
      self.result = {'content': result,
                     'status_code': 200,
                     'headers': [('Content-Type', 'text/html')]}
    self.status = status
    db.session.add(self)
    db.session.commit()

  def make_response(self, default=None):
    if self.result is None:
      return default
    from ggrc.app import app
    return app.make_response((self.result['content'],
                              self.result['status_code'],
                              self.result['headers']))


def create_task(name, url, queued_task=None, parameters={}):

  # task name must be unique
  task = BackgroundTask(name=name + str(int(time())))
  task.parameters = parameters
  task.modified_by = get_current_user()
  db.session.add(task)
  db.session.commit()

  # schedule a task queue
  if getattr(settings, 'APP_ENGINE', False):
    from google.appengine.api import taskqueue
    if request.method == "POST":
      headers = [h for h in request.headers if h[0] == 'Cookie']
    else:
      headers = request.headers
    taskqueue.add(
        queue_name="ggrc",
        url=url,
        name="{}_{}".format(task.name, task.id),
        params={'task_id': task.id},
        method=request.method,
        headers=headers)
  elif queued_task:
    queued_task(task)
  return task


def make_task_response(id):
  task = BackgroundTask.query.get(id)
  return task.make_response()


def queued_task(func):
  from ggrc.app import app

  @wraps(func)
  def decorated_view(*args, **kwargs):
    if len(args) > 0 and isinstance(args[0], BackgroundTask):
      task = args[0]
{'fraction_non_alphanumeric': 0.12042864432726655, 'fraction_numerical': 0.005273005613199524, 'mean_word_length': 3.0027229407760383, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1865017', 'n_tokens_mistral': 1839, 'n_tokens_neox': 1782, 'n_words': 452}