Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cherry pick changes from master #518

Merged
merged 4 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ below.
- David Matthews
- Mel Hall
- Christopher Bennett
- Mark Dawson
<!-- end-shortlog -->

(All contributors are identifiable with email addresses in the git version
Expand Down
37 changes: 28 additions & 9 deletions cylc/uiserver/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,11 @@
)

from cylc.uiserver.authorise import Authorization, AuthorizationMiddleware
from cylc.uiserver.resolvers import Resolvers
from cylc.uiserver.websockets import authenticated as websockets_authenticated
from cylc.uiserver.websockets.tornado import TornadoSubscriptionServer

if TYPE_CHECKING:
from cylc.uiserver.resolvers import Resolvers
from cylc.uiserver.websockets.tornado import TornadoSubscriptionServer
from graphql.execution import ExecutionResult


Expand Down Expand Up @@ -97,7 +98,7 @@ def is_token_authenticated(handler: 'CylcAppHandler') -> bool:
In these cases the bearer of the token is awarded full privileges.
"""
identity_provider: JPSIdentityProvider = (
handler.serverapp.identity_provider
handler.serverapp.identity_provider # type: ignore[union-attr]
)
return identity_provider.__class__ == PasswordIdentityProvider
# NOTE: not using isinstance to narrow this down to just the one class
Expand All @@ -122,17 +123,34 @@ def _authorise(
return False


def get_username(handler: 'CylcAppHandler'):
def get_initials(username: str):
if ('.' in username):
first, last = username.split('.', maxsplit=1)
return f"{first[0]}{last[0]}".upper()
elif (username != ''):
return username[0].upper()
else:
return None


def get_user_info(handler: 'CylcAppHandler'):
"""Return the username for the authenticated user.

If the handler is token authenticated, then we return the username of the
account that this server instance is running under.
"""
if is_token_authenticated(handler):
# the bearer of the token has full privileges
return ME
return {'name': ME, 'initials': get_initials(ME), 'username': ME}
else:
return handler.current_user.username
initials = handler.current_user.initials or get_initials(
handler.current_user.username
)
return {
'name': handler.current_user.name,
'initials': initials,
'username': handler.current_user.username
}


class CylcAppHandler(JupyterHandler):
Expand Down Expand Up @@ -247,7 +265,8 @@ def set_default_headers(self) -> None:
# @authorised TODO: I can't think why we would want to authorise this
def get(self):
user_info = {
'name': get_username(self)
**self.current_user.__dict__,
**get_user_info(self)
}

# add an entry for the workflow owner
Expand Down Expand Up @@ -316,7 +335,7 @@ def context(self):
'graphql_params': self.graphql_params,
'request': self.request,
'resolvers': self.resolvers,
'current_user': get_username(self),
'current_user': get_user_info(self)['username'],
}

@web.authenticated # type: ignore[arg-type]
Expand Down Expand Up @@ -384,7 +403,7 @@ def context(self):
return {
'request': self.request,
'resolvers': self.resolvers,
'current_user': get_username(self),
'current_user': get_user_info(self)['username'],
'ops_queue': {},
'sub_statuses': self.sub_statuses
}
20 changes: 17 additions & 3 deletions cylc/uiserver/resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,15 @@ async def clean(
await workflows_mgr.scan()
return cls._return("Workflow(s) cleaned")

@classmethod
async def scan(
cls,
args: dict,
workflows_mgr: 'WorkflowsManager',
):
await workflows_mgr.scan()
return cls._return("Scan requested")

@classmethod
async def play(cls, workflows, args, workflows_mgr, log):
"""Calls `cylc play`."""
Expand Down Expand Up @@ -534,24 +543,29 @@ async def service(
info: 'ResolveInfo',
command: str,
workflows: Iterable['Tokens'],
kwargs: Dict[str, Any]
kwargs: Dict[str, Any],
) -> List[Union[bool, str]]:
if command == 'clean':

if command == 'clean': # noqa: SIM116
return await Services.clean(
workflows,
kwargs,
self.workflows_mgr,
log=self.log,
executor=self.executor
)

elif command == 'play':
return await Services.play(
workflows,
kwargs,
self.workflows_mgr,
log=self.log
)
elif command == 'scan':
return await Services.scan(
kwargs,
self.workflows_mgr
)

raise NotImplementedError()

Expand Down
12 changes: 12 additions & 0 deletions cylc/uiserver/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,17 @@ class Arguments:
result = GenericScalar()


class Scan(graphene.Mutation):
class Meta:
description = sstrip('''
Scan the filesystem for file changes.

Valid for: stopped workflows.
''')
resolver = partial(mutator, command='scan')
result = GenericScalar()


async def get_jobs(root, info, **kwargs):
if kwargs['live']:
return await get_nodes_all(root, info, **kwargs)
Expand Down Expand Up @@ -545,6 +556,7 @@ class Logs(graphene.ObjectType):
class UISMutations(Mutations):
play = _mut_field(Play)
clean = _mut_field(Clean)
scan = _mut_field(Scan)


schema = graphene.Schema(
Expand Down
3 changes: 3 additions & 0 deletions cylc/uiserver/tests/test_authorise.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"reload",
"remove",
"resume",
"scan",
"set_graph_window_extent",
"set_hold_point",
"set_outputs",
Expand All @@ -66,6 +67,7 @@
"reload",
"remove",
"resume",
"scan",
"set_graph_window_extent",
"set_hold_point",
"set_outputs",
Expand Down Expand Up @@ -126,6 +128,7 @@
"play",
"trigger",
"resume",
"scan",
"set_verbosity",
"set_graph_window_extent",
"read",
Expand Down
6 changes: 5 additions & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[mypy]
python_version = 3.7
python_version = 3.8
ignore_missing_imports = True
files = cylc/uiserver
# don't run mypy on these files directly
Expand All @@ -14,3 +14,7 @@ explicit_package_bases = True
allow_redefinition = True
strict_equality = True
show_error_codes = True

# Suppress the following messages:
# By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
disable_error_code = annotation-unchecked
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ tests =
flake8-debugger>=4.0.0
flake8-mutable>=1.2.0
flake8-simplify>=0.14.0
flake8-type-checking
flake8>=3.0.0
jupyter_server[test]
mypy>=0.900
Expand Down
3 changes: 0 additions & 3 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ ignore=
W503,
; line break after binary operator
W504
; suggests using f"{!r}" instead of manual quotes (flake8-bugbear)
; Doesn't work at 3.7
B028

exclude=
build,
Expand Down