# Path: yawn/worker/models.py
# class Worker(models.Model):
#     """Information about current and past workers"""
#     #
#     # NOTE: consider instead taking an advisory lock for each worker,
#     # and using it to check if a worker is still connected.
#     # See `pg_try_advisory_lock` and `select * from pg_locks where locktype = 'advisory'`
#     # That would give more immediate feedback, but its not clear we need to be faster.
#     #
#     ACTIVE = 'active'
#     EXITED = 'exited'
#     LOST = 'lost'
#     STATUS_CHOICES = [(x, x) for x in (ACTIVE, EXITED, LOST)]
# 
#     name = models.TextField(blank=False)
#     status = models.TextField(choices=STATUS_CHOICES, default=ACTIVE)
#     start_timestamp = models.DateTimeField(default=functions.Now)
#     last_heartbeat = models.DateTimeField(default=functions.Now)
# 
#     @staticmethod
#     def find_lost(timeout):
#         from yawn.task.models import Execution
# 
#         # Make a sparse index so looking up active workers is fast:
#         # CREATE INDEX yawn_worker_active ON yawn_worker (status) WHERE status = 'active'
#         lost = Worker.objects.filter(
#             status=Worker.ACTIVE, last_heartbeat__lt=functions.Now() - timedelta(seconds=timeout)
#         )
#         for worker in lost:
#             logger.warning('Marking %r as lost', worker)
#             worker.status = Worker.LOST
#             worker.save()
# 
#             executions = worker.execution_set.filter(status=Execution.RUNNING)
# 
#             for execution in executions:
#                 logger.warning('Marking %r as lost', execution)
#                 execution.mark_finished(lost=True)
# 
#     def __str__(self):
#         return self.name
# 
# class Queue(models.Model):
#     """Arbitrary tag defining where tasks run."""
# 
#     name = models.TextField(unique=True)
# 
#     _default = None
# 
#     def __str__(self):
#         return self.name
# 
#     @classmethod
#     def get_default_queue(cls):
#         if not cls._default:
#             cls._default = Queue.objects.get_or_create(name='default')[0]
#         return cls._default
# 
# Path: yawn/worker/serializers.py
# class WorkerSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Worker
#         fields = '__all__'
# 
# class QueueSerializer(serializers.ModelSerializer):
#     message_count = serializers.IntegerField(read_only=True, source='message__count')
#     purge = serializers.BooleanField(write_only=True, default=False)
# 
#     class Meta:
#         model = Queue
#         fields = '__all__'
# 
#     def update(self, instance, validated_data):
#         if validated_data['purge'] is True:
#             instance.message_set.all().delete()
#             instance.message__count = 0
#         return instance


from django.db.models import Count
from rest_framework import viewsets
from yawn.worker.models import Worker, Queue
from yawn.worker.serializers import WorkerSerializer, QueueSerializer



class WorkerViewSet(viewsets.GenericViewSet,
                    viewsets.mixins.ListModelMixin,
                    viewsets.mixins.RetrieveModelMixin):
    """
    Worker endpoint, GET(list)
    """

# Path: yawn/worker/models.py
# class Worker(models.Model):
#     """Information about current and past workers"""
#     #
#     # NOTE: consider instead taking an advisory lock for each worker,
#     # and using it to check if a worker is still connected.
#     # See `pg_try_advisory_lock` and `select * from pg_locks where locktype = 'advisory'`
#     # That would give more immediate feedback, but its not clear we need to be faster.
#     #
#     ACTIVE = 'active'
#     EXITED = 'exited'
#     LOST = 'lost'
#     STATUS_CHOICES = [(x, x) for x in (ACTIVE, EXITED, LOST)]
# 
#     name = models.TextField(blank=False)
#     status = models.TextField(choices=STATUS_CHOICES, default=ACTIVE)
#     start_timestamp = models.DateTimeField(default=functions.Now)
#     last_heartbeat = models.DateTimeField(default=functions.Now)
# 
#     @staticmethod
#     def find_lost(timeout):
#         from yawn.task.models import Execution
# 
#         # Make a sparse index so looking up active workers is fast:
#         # CREATE INDEX yawn_worker_active ON yawn_worker (status) WHERE status = 'active'
#         lost = Worker.objects.filter(
#             status=Worker.ACTIVE, last_heartbeat__lt=functions.Now() - timedelta(seconds=timeout)
#         )
#         for worker in lost:
#             logger.warning('Marking %r as lost', worker)
#             worker.status = Worker.LOST
#             worker.save()
# 
#             executions = worker.execution_set.filter(status=Execution.RUNNING)
# 
#             for execution in executions:
#                 logger.warning('Marking %r as lost', execution)
#                 execution.mark_finished(lost=True)
# 
#     def __str__(self):
#         return self.name
# 
# class Queue(models.Model):
#     """Arbitrary tag defining where tasks run."""
# 
#     name = models.TextField(unique=True)
# 
#     _default = None
# 
#     def __str__(self):
#         return self.name
# 
#     @classmethod
#     def get_default_queue(cls):
#         if not cls._default:
#             cls._default = Queue.objects.get_or_create(name='default')[0]
#         return cls._default
# 
# Path: yawn/worker/serializers.py
# class WorkerSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Worker
#         fields = '__all__'
# 
# class QueueSerializer(serializers.ModelSerializer):
#     message_count = serializers.IntegerField(read_only=True, source='message__count')
#     purge = serializers.BooleanField(write_only=True, default=False)
# 
#     class Meta:
#         model = Queue
#         fields = '__all__'
# 
#     def update(self, instance, validated_data):
#         if validated_data['purge'] is True:
#             instance.message_set.all().delete()
#             instance.message__count = 0
#         return instance


# Path: yawn/worker/views.py
from django.db.models import Count
from rest_framework import viewsets
from yawn.worker.models import Worker, Queue
from yawn.worker.serializers import WorkerSerializer, QueueSerializer




class WorkerViewSet(viewsets.GenericViewSet,
                    viewsets.mixins.ListModelMixin,
                    viewsets.mixins.RetrieveModelMixin):
    """
    Worker endpoint, GET(list)
    """

    queryset = Worker.objects.all().order_by('-id')