'Atomically creates a new transaction for this application service
with the given list of events.
Args:
service(ApplicationService): The service who the transaction is for.
events(list<Event>): A list of events to put in the transaction.
Returns:
AppServiceTransaction: A new transaction.'

def create_appservice_txn(self, service, events):

    def _create_appservice_txn(txn):
        last_txn_id = self._get_last_txn(txn, service.id)
        txn.execute('SELECT    MAX(txn_id)    FROM    application_services_txns    WHERE    as_id=?', (service.id,))
        highest_txn_id = txn.fetchone()[0]
        if (highest_txn_id is None):
            highest_txn_id = 0
        new_txn_id = (max(highest_txn_id, last_txn_id) + 1)
        event_ids = json.dumps([e.event_id for e in events])
        txn.execute('INSERT    INTO    application_services_txns(as_id,    txn_id,    event_ids)    VALUES(?,?,?)', (service.id, new_txn_id, event_ids))
        return AppServiceTransaction(service=service, id=new_txn_id, events=events)
    return self.runInteraction('create_appservice_txn', _create_appservice_txn)
