Skip to content

Commit

Permalink
✨ Add api to deactivate workers
Browse files Browse the repository at this point in the history
  • Loading branch information
pajowu committed Nov 19, 2023
1 parent d670825 commit 6237d52
Show file tree
Hide file tree
Showing 6 changed files with 192 additions and 22 deletions.
57 changes: 54 additions & 3 deletions backend/openapi-schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,16 @@ components:
- name
title: CreateWorker
type: object
DeactivateWorker:
properties:
id:
format: uuid
title: Id
type: string
required:
- id
title: DeactivateWorker
type: object
Document:
properties:
changed_at:
Expand Down Expand Up @@ -572,6 +582,10 @@ components:
type: object
Worker:
properties:
deactivated_at:
format: date-time
title: Deactivated At
type: string
id:
format: uuid
title: Id
Expand All @@ -591,8 +605,16 @@ components:
- token
title: Worker
type: object
WorkerBase:
WorkerWithId:
properties:
deactivated_at:
format: date-time
title: Deactivated At
type: string
id:
format: uuid
title: Id
type: string
last_seen:
format: date-time
title: Last Seen
Expand All @@ -602,7 +624,7 @@ components:
type: string
required:
- name
title: WorkerBase
title: WorkerWithId
type: object
info:
title: FastAPI
Expand Down Expand Up @@ -1453,7 +1475,7 @@ paths:
application/json:
schema:
items:
$ref: '#/components/schemas/WorkerBase'
$ref: '#/components/schemas/WorkerWithId'
title: Response List Workers Api V1 Worker Get
type: array
description: Successful Response
Expand Down Expand Up @@ -1494,6 +1516,35 @@ paths:
$ref: '#/components/schemas/HTTPValidationError'
description: Validation Error
summary: Create Worker Endpoint
/api/v1/worker/deactivate/:
post:
operationId: deactivate_worker_endpoint_api_v1_worker_deactivate__post
parameters:
- in: header
name: Api-Token
required: true
schema:
title: Api-Token
type: string
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/DeactivateWorker'
required: true
responses:
'200':
content:
application/json:
schema: {}
description: Successful Response
'422':
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
description: Validation Error
summary: Deactivate Worker Endpoint
/media/{file}:
get:
operationId: serve_media_media__file__get
Expand Down
6 changes: 4 additions & 2 deletions backend/transcribee_backend/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ def validate_worker_authorization(session: Session, authorization: str) -> Worke
if token_type != "Worker":
raise HTTPException(status_code=401)

statement = select(Worker).where(Worker.token == token)
statement = select(Worker).where(
Worker.token == token, col(Worker.deactivated_at).is_(None)
)
worker = session.exec(statement).one_or_none()
if worker is None:
raise HTTPException(status_code=401)
Expand Down Expand Up @@ -223,7 +225,7 @@ def validate_api_token_authorization(session: Session, api_token: str):

def create_worker(session: Session, name: str) -> Worker:
token = b64encode(os.urandom(32)).decode()
worker = Worker(name=name, token=token, last_seen=None)
worker = Worker(name=name, token=token, last_seen=None, deactivated_at=None)
session.add(worker)
session.commit()
return worker
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Add Worker.deactivated_at flag
Revision ID: 417eece003cb
Revises: 937846561faf
Create Date: 2023-11-18 17:14:05.221788
"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "417eece003cb"
down_revision = "937846561faf"
branch_labels = None
depends_on = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("worker", schema=None) as batch_op:
batch_op.add_column(
sa.Column("deactivated_at", sa.DateTime(timezone=True), nullable=True)
)

# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("worker", schema=None) as batch_op:
batch_op.drop_column("deactivated_at")

# ### end Alembic commands ###
8 changes: 7 additions & 1 deletion backend/transcribee_backend/models/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,19 @@ class WorkerBase(SQLModel):
last_seen: Optional[datetime.datetime] = Field(
sa_column=Column(DateTime(timezone=True), nullable=True)
)
deactivated_at: Optional[datetime.datetime] = Field(
sa_column=Column(DateTime(timezone=True), nullable=True)
)


class Worker(WorkerBase, table=True):
class WorkerWithId(WorkerBase):
id: uuid.UUID = Field(
default_factory=uuid.uuid4,
primary_key=True,
index=True,
nullable=False,
)


class Worker(WorkerWithId, table=True):
token: str
50 changes: 37 additions & 13 deletions backend/transcribee_backend/routers/worker.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import uuid
from typing import List

from fastapi import APIRouter, Depends
from sqlmodel import Session, select
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session, col, select
from sqlmodel.main import SQLModel

from transcribee_backend.auth import (
create_worker,
get_api_token,
)
from transcribee_backend.auth import create_worker, get_api_token
from transcribee_backend.db import get_session
from transcribee_backend.models import (
ApiToken,
)
from transcribee_backend.models.worker import Worker, WorkerBase
from transcribee_backend.helpers.time import now_tz_aware
from transcribee_backend.models import ApiToken
from transcribee_backend.models.worker import Worker, WorkerWithId

worker_router = APIRouter()

Expand All @@ -21,6 +18,10 @@ class CreateWorker(SQLModel):
name: str


class DeactivateWorker(SQLModel):
id: uuid.UUID


@worker_router.post("/create/")
def create_worker_endpoint(
worker: CreateWorker,
Expand All @@ -34,9 +35,32 @@ def create_worker_endpoint(
def list_workers(
session: Session = Depends(get_session),
_token: ApiToken = Depends(get_api_token),
) -> List[WorkerBase]:
statement = select(Worker)
) -> List[WorkerWithId]:
statement = select(Worker).where(col(Worker.deactivated_at).is_(None))
return [
WorkerBase(name=worker.name, last_seen=worker.last_seen)
WorkerWithId(
name=worker.name,
last_seen=worker.last_seen,
id=worker.id,
deactivated_at=worker.deactivated_at,
)
for worker in session.exec(statement).all()
]


@worker_router.post("/deactivate/")
def deactivate_worker_endpoint(
body: DeactivateWorker,
session: Session = Depends(get_session),
_token: ApiToken = Depends(get_api_token),
) -> None:
query = select(Worker).where(
Worker.id == body.id, col(Worker.deactivated_at).is_(None)
)
result = session.exec(query).one_or_none()
if result is None:
raise HTTPException(status_code=404, detail="Worker not found.")

result.deactivated_at = now_tz_aware()
session.add(result)
session.commit()
60 changes: 57 additions & 3 deletions frontend/src/openapi-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ export interface paths {
/** Create Worker Endpoint */
post: operations["create_worker_endpoint_api_v1_worker_create__post"];
};
"/api/v1/worker/deactivate/": {
/** Deactivate Worker Endpoint */
post: operations["deactivate_worker_endpoint_api_v1_worker_deactivate__post"];
};
"/media/{file}": {
/** Serve Media */
get: operations["serve_media_media__file__get"];
Expand Down Expand Up @@ -240,6 +244,14 @@ export interface components {
/** Name */
name: string;
};
/** DeactivateWorker */
DeactivateWorker: {
/**
* Id
* Format: uuid
*/
id: string;
};
/** Document */
Document: {
/** Changed At */
Expand Down Expand Up @@ -465,6 +477,11 @@ export interface components {
};
/** Worker */
Worker: {
/**
* Deactivated At
* Format: date-time
*/
deactivated_at?: string;
/**
* Id
* Format: uuid
Expand All @@ -480,8 +497,18 @@ export interface components {
/** Token */
token: string;
};
/** WorkerBase */
WorkerBase: {
/** WorkerWithId */
WorkerWithId: {
/**
* Deactivated At
* Format: date-time
*/
deactivated_at?: string;
/**
* Id
* Format: uuid
*/
id?: string;
/**
* Last Seen
* Format: date-time
Expand Down Expand Up @@ -1184,7 +1211,7 @@ export interface operations {
/** @description Successful Response */
200: {
content: {
"application/json": (components["schemas"]["WorkerBase"])[];
"application/json": components["schemas"]["WorkerWithId"][];
};
};
/** @description Validation Error */
Expand Down Expand Up @@ -1222,6 +1249,33 @@ export interface operations {
};
};
};
/** Deactivate Worker Endpoint */
deactivate_worker_endpoint_api_v1_worker_deactivate__post: {
parameters: {
header: {
"Api-Token": string;
};
};
requestBody: {
content: {
"application/json": components["schemas"]["DeactivateWorker"];
};
};
responses: {
/** @description Successful Response */
200: {
content: {
"application/json": unknown;
};
};
/** @description Validation Error */
422: {
content: {
"application/json": components["schemas"]["HTTPValidationError"];
};
};
};
};
/** Serve Media */
serve_media_media__file__get: {
parameters: {
Expand Down

0 comments on commit 6237d52

Please sign in to comment.