\ No newline at end of file
diff --git a/DataFileUtil.spec b/DataFileUtil.spec
index fb3fdd6..2c786b9 100644
--- a/DataFileUtil.spec
+++ b/DataFileUtil.spec
@@ -350,13 +350,11 @@ module DataFileUtil {
information to use the latest version.
data - the object data.
- Optional parameters:
- One of an object name or id. If no name or id is provided the name
- will be set to 'auto' with the object id appended as a string,
- possibly with -\d+ appended if that object id already exists as a
- name.
+ One of an object name or id:
name - the name of the object.
objid - the id of the object to save over.
+
+ Optional parameters:
meta - arbitrary user-supplied metadata for the object,
not to exceed 16kb; if the object type specifies automatic
metadata extraction with the 'meta ws' annotation, and your
@@ -403,8 +401,16 @@ module DataFileUtil {
} SaveObjectsParams;
/*
- Save objects to the workspace. Saving over a deleted object undeletes
- it.
+ Save objects to the workspace.
+
+ The objects will be sorted prior to saving to avoid the Workspace sort memory limit.
+ Note that if the object contains workspace object refs in mapping keys that may cause
+ the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA
+ format (e.g. #/#/#, where # is a positive integer).
+
+ If the data is very large, using the WSLargeDataIO SDK module is advised.
+
+ Saving over a deleted object undeletes it.
*/
funcdef save_objects(SaveObjectsParams params)
returns (list info) authentication required;
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 8b22342..13f81ce 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -1,17 +1,23 @@
-#0.1.3
+# 0.1.4
+- objects saved to the workspace are now sorted prior to serialization. This prevents errors due
+ to workspace sort memory limits, and also moves the sort compute load (which is the most
+ expensive part of saving objects) from the workspace server node to the SDK job nodes.
+
+# 0.1.3
- tidying for github consistency
- Added Actions workflow for KB SDK tests
- Added Dependabot and LGTM configurations
- Updated `README.md` to include standard build, coverage, and LGTM badging.
-#0.1.2
+# 0.1.2
- deprecate handle service with handle service 2
-- replace the colon(:) [that was reported to have caused download error for Windows users] with underscore in shock filenames
+- replace the colon(:) [that was reported to have caused download error for Windows users] with
+ underscore in shock filenames
-#0.1.1
+# 0.1.1
- close no longer used sockets.
-#0.1.0
+# 0.1.0
- shock attributes are now ignored on upload. In a future release they will be removed altogether
and specifying attributes for upload will be an error.
- shock indexes and attributes are no longer copied during a copy or ownership operation.
diff --git a/lib/DataFileUtil/DataFileUtilClient.py b/lib/DataFileUtil/DataFileUtilClient.py
index 2117a23..2c33d69 100644
--- a/lib/DataFileUtil/DataFileUtilClient.py
+++ b/lib/DataFileUtil/DataFileUtilClient.py
@@ -357,8 +357,13 @@ def ws_name_to_id(self, name, context=None):
def save_objects(self, params, context=None):
"""
- Save objects to the workspace. Saving over a deleted object undeletes
- it.
+ Save objects to the workspace.
+ The objects will be sorted prior to saving to avoid the Workspace sort memory limit.
+ Note that if the object contains workspace object refs in mapping keys that may cause
+ the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA
+ format (e.g. #/#/#, where # is a positive integer).
+ If the data is very large, using the WSLargeDataIO SDK module is advised.
+ Saving over a deleted object undeletes it.
:param params: instance of type "SaveObjectsParams" (Input parameters
for the "save_objects" function. Required parameters: id - the
numerical ID of the workspace. objects - the objects to save. The
@@ -367,15 +372,12 @@ def save_objects(self, params, context=None):
type "ObjectSaveData" (An object and associated data required for
saving. Required parameters: type - the workspace type string for
the object. Omit the version information to use the latest
- version. data - the object data. Optional parameters: One of an
- object name or id. If no name or id is provided the name will be
- set to 'auto' with the object id appended as a string, possibly
- with -\d+ appended if that object id already exists as a name.
- name - the name of the object. objid - the id of the object to
- save over. meta - arbitrary user-supplied metadata for the object,
- not to exceed 16kb; if the object type specifies automatic
- metadata extraction with the 'meta ws' annotation, and your
- metadata name conflicts, then your metadata will be silently
+ version. data - the object data. One of an object name or id: name
+ - the name of the object. objid - the id of the object to save
+ over. Optional parameters: meta - arbitrary user-supplied metadata
+ for the object, not to exceed 16kb; if the object type specifies
+ automatic metadata extraction with the 'meta ws' annotation, and
+ your metadata name conflicts, then your metadata will be silently
overwritten. hidden - true if this object should not be listed
when listing workspace objects. extra_provenance_input_refs -
(optional) if set, these refs will be appended to the primary
diff --git a/lib/DataFileUtil/DataFileUtilImpl.py b/lib/DataFileUtil/DataFileUtilImpl.py
index 16c8610..11818a8 100644
--- a/lib/DataFileUtil/DataFileUtilImpl.py
+++ b/lib/DataFileUtil/DataFileUtilImpl.py
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
#BEGIN_HEADER
-import copy
import errno
import ftplib
import gzip
@@ -12,7 +11,6 @@
import subprocess
import tarfile
import tempfile
-import time
import uuid
import zipfile
@@ -22,6 +20,8 @@
import semver
from requests_toolbelt.multipart.encoder import MultipartEncoder
+from DataFileUtil.implementation import log, save_objects
+
from installed_clients.AbstractHandleClient import AbstractHandle as HandleService
from installed_clients.WorkspaceClient import Workspace
from installed_clients.baseclient import ServerError as HandleError
@@ -56,9 +56,9 @@ class DataFileUtil:
# state. A method could easily clobber the state set by another while
# the latter method is running.
######################################### noqa
- VERSION = "0.1.2"
- GIT_URL = "git@github.com:kbaseapps/DataFileUtil.git"
- GIT_COMMIT_HASH = "d8091ef8acdee21c5b43d1b84d3983b04be3729e"
+ VERSION = "0.1.3"
+ GIT_URL = "https://github.com/kbaseapps/DataFileUtil.git"
+ GIT_COMMIT_HASH = "df19d64a4a70c6ab32d6248a216bc25be0ac35ba"
#BEGIN_CLASS_HEADER
@@ -82,10 +82,6 @@ class DataFileUtil:
STAGING_GLOBAL_FILE_PREFIX = '/data/bulk/'
STAGING_USER_FILE_PREFIX = '/staging/'
- def log(self, message, prefix_newline=False):
- print(('\n' if prefix_newline else '') +
- str(time.time()) + ': ' + str(message))
-
def endswith(self, string, suffixes):
strl = string.lower()
for s in suffixes:
@@ -97,10 +93,10 @@ def endswith(self, string, suffixes):
# don't see a way to do that
def gzip(self, oldfile):
if self.endswith(oldfile, [self.GZ, self.GZIP, self.TGZ]):
- self.log('File {} is already gzipped, skipping'.format(oldfile))
+ log('File {} is already gzipped, skipping'.format(oldfile))
return oldfile
newfile = oldfile + self.GZ
- self.log('gzipping {} to {}'.format(oldfile, newfile))
+ log('gzipping {} to {}'.format(oldfile, newfile))
with open(oldfile, 'rb') as s, gzip.open(newfile, 'wb') as t:
shutil.copyfileobj(s, t)
return newfile
@@ -109,10 +105,10 @@ def gzip(self, oldfile):
# the pigz parallel compression program
def _pigz_compress(self, oldfile, n_proc=None, compression_level=None):
if self.endswith(oldfile, [self.GZ, self.GZIP, self.TGZ]):
- self.log('File {} is already gzipped, skipping'.format(oldfile))
+ log('File {} is already gzipped, skipping'.format(oldfile))
return oldfile
newfile = oldfile + self.GZ
- self.log('gzipping (with pigz) {} to {}'.format(oldfile, newfile))
+ log('gzipping (with pigz) {} to {}'.format(oldfile, newfile))
# -f to force overwrite
# --keep to retain the original file
@@ -158,7 +154,7 @@ def _pack(self, file_path, pack):
if not f:
f = os.path.basename(d)
file_path = d + os.sep + f
- self.log('Packing {} to {}'.format(d, pack))
+ log('Packing {} to {}'.format(d, pack))
# tar is smart enough to not pack its own archive file into the new archive, zip isn't.
# TODO is there a designated temp files dir in the scratch space? Nope.
# check dir to archive is not self.tmp or its parent dir for zip
@@ -195,7 +191,7 @@ def _decompress_file_name(self, file_path):
def _decompress(self, openfn, file_path, unpack):
new_file = self._decompress_file_name(file_path)
- self.log('decompressing {} to {} ...'.format(file_path, new_file))
+ log('decompressing {} to {} ...'.format(file_path, new_file))
with openfn(file_path, 'rb') as s, tempfile.NamedTemporaryFile(
dir=self.tmp, delete=False) as tf:
# don't create the target file until it's done decompressing
@@ -211,7 +207,7 @@ def _decompress(self, openfn, file_path, unpack):
# of the passed in file open function
def _pigz_decompress(self, file_path, unpack, n_proc=None):
new_file = self._decompress_file_name(file_path)
- self.log('decompressing (with pigz) {} to {} ...'.format(file_path, new_file))
+ log('decompressing (with pigz) {} to {} ...'.format(file_path, new_file))
# --keep to retain the original file
# --processes to limit the number of processes
@@ -250,7 +246,7 @@ def _unarchive(self, file_path, unpack, file_type):
raise ValueError(
'File {} is tar file but only uncompress was specified'
.format(file_path))
- self.log('unpacking {} ...'.format(file_path))
+ log('unpacking {} ...'.format(file_path))
with tarfile.open(file_path) as tf:
self._check_members(tf.getnames())
tf.extractall(file_dir)
@@ -260,7 +256,7 @@ def _unarchive(self, file_path, unpack, file_type):
raise ValueError(
'File {} is zip file but only uncompress was specified'
.format(file_path))
- self.log('unpacking {} ...'.format(file_path))
+ log('unpacking {} ...'.format(file_path))
with zipfile.ZipFile(file_path) as zf:
self._check_members(zf.namelist())
zf.extractall(file_dir)
@@ -273,7 +269,7 @@ def _check_members(self, member_list):
if n.startswith('/') or n.startswith('..'):
err = ('Dangerous archive file - entry [{}] points to a ' +
'file outside the archive directory').format(m)
- self.log(err)
+ log(err)
raise ValueError(err)
def _unpack(self, file_path, unpack):
@@ -308,7 +304,7 @@ def check_shock_response(self, response, errtxt):
err = json.loads(response.content)['error'][0]
except:
# this means shock is down or not responding.
- self.log("Couldn't parse response error content from Shock: " +
+ log("Couldn't parse response error content from Shock: " +
response.content)
response.raise_for_status()
raise ShockException(errtxt + str(err))
@@ -382,7 +378,7 @@ def _retrieve_filepath(self, file_url, cookies=None):
try:
content_disposition = response.headers['content-disposition']
except KeyError:
- self.log('Parsing file name directly from URL')
+ log('Parsing file name directly from URL')
file_name = file_url.split('/')[-1]
else:
file_name = content_disposition.split('filename="')[-1].split('";')[0]
@@ -391,7 +387,7 @@ def _retrieve_filepath(self, file_url, cookies=None):
error_msg += 'Exception: {}'.format(error)
raise ValueError(error_msg)
- self.log('Retrieving file name from url: {}'.format(file_name))
+ log('Retrieving file name from url: {}'.format(file_name))
copy_file_path = os.path.join(self.tmp, file_name)
return copy_file_path
@@ -407,8 +403,8 @@ def _wget_dl(self, url, destination_file, try_number=20, time_out=1800):
try:
download_state=subprocess.call(command)
except Exception as e:
- self.log('Error running wget')
- self.log(e)
+ log('Error running wget')
+ log(e)
return download_state
@@ -422,7 +418,7 @@ def _download_to_file(self, file_url):
"""
copy_file_path = self._retrieve_filepath(file_url)
- self.log('Connecting and downloading web source: {}'.format(
+ log('Connecting and downloading web source: {}'.format(
file_url))
success = False
@@ -439,7 +435,7 @@ def _download_to_file(self, file_url):
if not success:
raise ValueError('Dowload Failed!')
- self.log('Downloaded file to {}'.format(copy_file_path))
+ log('Downloaded file to {}'.format(copy_file_path))
return copy_file_path
@@ -469,14 +465,14 @@ def _download_dropbox_link(self, file_url):
if not file_url.startswith('https://www.dropbox.com/'):
raise ValueError('Invalid DropBox Link: {}'.format(file_url))
- self.log('Connecting DropBox link: {}'.format(file_url))
+ log('Connecting DropBox link: {}'.format(file_url))
# translate dropbox URL for direct download
if "?" not in file_url:
force_download_link = file_url + '?raw=1'
else:
force_download_link = file_url.partition('?')[0] + '?raw=1'
- self.log('Generating DropBox direct download link\n' +
+ log('Generating DropBox direct download link\n' +
' from: {}\n to: {}'.format(file_url, force_download_link))
copy_file_path = self._download_to_file(force_download_link)
@@ -502,7 +498,7 @@ def _download_google_drive_to_file(self, file_url, cookies=None):
"""
copy_file_path = self._retrieve_filepath(file_url, cookies)
- self.log('Connecting and downloading web source: {}'.format(
+ log('Connecting and downloading web source: {}'.format(
file_url))
try:
@@ -510,7 +506,7 @@ def _download_google_drive_to_file(self, file_url, cookies=None):
with open(copy_file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
- self.log('Downloaded file to {}'.format(copy_file_path))
+ log('Downloaded file to {}'.format(copy_file_path))
except BaseException as error:
error_msg = 'Cannot connect to URL: {}\n'.format(file_url)
error_msg += 'Exception: {}'.format(error)
@@ -530,7 +526,7 @@ def _download_google_drive_link(self, file_url):
if not file_url.startswith('https://drive.google.com/'):
raise ValueError('Invalid Google Drive Link: {}'.format(file_url))
- self.log('Connecting Google Drive link: {}'.format(file_url))
+ log('Connecting Google Drive link: {}'.format(file_url))
# translate Google Drive URL for direct download
force_download_link_prefix = 'https://docs.google.com/uc?export=download'
@@ -552,7 +548,7 @@ def _download_google_drive_link(self, file_url):
if confirm_token:
force_download_link = force_download_link_prefix + '&confirm={}&id={}'.format(confirm_token, file_id)
- self.log('Generating Google Drive direct download link\n' +
+ log('Generating Google Drive direct download link\n' +
' from: {}\n to: {}'.format(file_url, force_download_link))
copy_file_path = self._download_google_drive_to_file(force_download_link, response.cookies)
@@ -577,7 +573,7 @@ def _download_ftp_link(self, file_url):
if not file_url.startswith('ftp://'):
raise ValueError('Invalid FTP Link: {}'.format(file_url))
- self.log('Connecting FTP link: {}'.format(file_url))
+ log('Connecting FTP link: {}'.format(file_url))
ftp_url_format = re.match(r'ftp://.*:.*@.*/.*', file_url)
# process ftp credentials
if ftp_url_format:
@@ -592,7 +588,7 @@ def _download_ftp_link(self, file_url):
ftp_file_name = re.search(
'ftp://.*:.*@.*/(.+$)', file_url).group(1)
else:
- self.log('Setting anonymous FTP user_name and password')
+ log('Setting anonymous FTP user_name and password')
ftp_user_name = 'anonymous'
ftp_password = 'anonymous@domain.com'
ftp_domain = re.search('ftp://(.+?)/', file_url).group(1)
@@ -612,7 +608,7 @@ def _download_ftp_link(self, file_url):
with open(copy_file_path, 'wb') as output:
ftp_connection.retrbinary('RETR {}'.format(ftp_file_name),
output.write)
- self.log('Copied FTP file to: {}'.format(copy_file_path))
+ log('Copied FTP file to: {}'.format(copy_file_path))
copy_file_path = self._unpack(copy_file_path, True)
@@ -662,9 +658,9 @@ def __init__(self, config):
# note that the unit tests cannot easily test this. Be careful with changes here
with requests.get(config['kbase-endpoint'] + '/shock-direct', allow_redirects=False) as r:
if r.status_code == 302:
- self.log('Using direct shock url for transferring files')
+ log('Using direct shock url for transferring files')
self.shock_effective = r.headers['Location']
- self.log('Shock url: ' + self.shock_effective)
+ log('Shock url: ' + self.shock_effective)
self.handle_url = config['handle-service-url']
self.ws_url = config['workspace-url']
self.scratch = config['scratch']
@@ -731,7 +727,7 @@ def shock_to_file(self, ctx, params):
shock_url = self.shock_effective
if handle_id:
- self.log('Fetching info for handle: '+handle_id)
+ log('Fetching info for handle: '+handle_id)
hs = HandleService(self.handle_url, token=token)
handles = hs.hids_to_handles([handle_id])
# don't override direct url if provided
@@ -755,7 +751,7 @@ def shock_to_file(self, ctx, params):
attributes = resp_obj['data']['attributes']
if os.path.isdir(file_path):
file_path = os.path.join(file_path, node_file_name)
- self.log('downloading shock node ' + shock_id + ' into file: ' + str(file_path))
+ log('downloading shock node ' + shock_id + ' into file: ' + str(file_path))
with open(file_path, 'wb') as fhandle:
with requests.get(node_url + '?download_raw', stream=True,
headers=headers, allow_redirects=True) as r:
@@ -773,7 +769,7 @@ def shock_to_file(self, ctx, params):
'attributes': attributes,
'file_path': file_path,
'size': size}
- self.log('downloading done')
+ log('downloading done')
#END shock_to_file
# At some point might do deeper type checking...
@@ -895,7 +891,7 @@ def file_to_shock(self, ctx, params):
pack = params.get('pack')
if pack:
file_path = self._pack(file_path, pack)
- self.log('uploading file ' + str(file_path) + ' into shock node')
+ log('uploading file ' + str(file_path) + ' into shock node')
with open(os.path.abspath(file_path), 'rb') as data_file:
# Content-Length header is required for transition to
# https://github.com/kbase/blobstore
@@ -917,7 +913,7 @@ def file_to_shock(self, ctx, params):
'size': shock_data['file']['size']}
if params.get('make_handle'):
out['handle'] = self.make_handle(shock_data, token)
- self.log('uploading done into shock node: ' + shock_id)
+ log('uploading done into shock node: ' + shock_id)
#END file_to_shock
# At some point might do deeper type checking...
@@ -1298,8 +1294,13 @@ def ws_name_to_id(self, ctx, name):
def save_objects(self, ctx, params):
"""
- Save objects to the workspace. Saving over a deleted object undeletes
- it.
+ Save objects to the workspace.
+ The objects will be sorted prior to saving to avoid the Workspace sort memory limit.
+ Note that if the object contains workspace object refs in mapping keys that may cause
+ the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA
+ format (e.g. #/#/#, where # is a positive integer).
+ If the data is very large, using the WSLargeDataIO SDK module is advised.
+ Saving over a deleted object undeletes it.
:param params: instance of type "SaveObjectsParams" (Input parameters
for the "save_objects" function. Required parameters: id - the
numerical ID of the workspace. objects - the objects to save. The
@@ -1308,15 +1309,12 @@ def save_objects(self, ctx, params):
type "ObjectSaveData" (An object and associated data required for
saving. Required parameters: type - the workspace type string for
the object. Omit the version information to use the latest
- version. data - the object data. Optional parameters: One of an
- object name or id. If no name or id is provided the name will be
- set to 'auto' with the object id appended as a string, possibly
- with -\d+ appended if that object id already exists as a name.
- name - the name of the object. objid - the id of the object to
- save over. meta - arbitrary user-supplied metadata for the object,
- not to exceed 16kb; if the object type specifies automatic
- metadata extraction with the 'meta ws' annotation, and your
- metadata name conflicts, then your metadata will be silently
+ version. data - the object data. One of an object name or id: name
+ - the name of the object. objid - the id of the object to save
+ over. Optional parameters: meta - arbitrary user-supplied metadata
+ for the object, not to exceed 16kb; if the object type specifies
+ automatic metadata extraction with the 'meta ws' annotation, and
+ your metadata name conflicts, then your metadata will be silently
overwritten. hidden - true if this object should not be listed
when listing workspace objects. extra_provenance_input_refs -
(optional) if set, these refs will be appended to the primary
@@ -1355,45 +1353,9 @@ def save_objects(self, ctx, params):
# ctx is the context object
# return variables are: info
#BEGIN save_objects
- prov = ctx.provenance()
- objs = params.get('objects')
- if not objs:
- raise ValueError('Required parameter objects missing')
- wsid = params.get('id')
- if not wsid:
- raise ValueError('Required parameter id missing')
- objs_to_save = []
- for o in objs:
- obj_to_save = {}
-
- prov_to_save = prov
- if 'extra_provenance_input_refs' in o:
- prov_to_save = copy.deepcopy(prov) # need to make a copy so we don't clobber other objects
- extra_input_refs = o['extra_provenance_input_refs']
- if extra_input_refs:
- if len(prov) > 0:
- if 'input_ws_objects' in prov[0]:
- prov_to_save[0]['input_ws_objects'].extend(extra_input_refs)
- else:
- prov_to_save[0]['input_ws_objects'] = extra_input_refs
- else:
- prov_to_save = [{'input_ws_objects': extra_input_refs}]
-
- keys = ['type', 'data', 'name', 'objid', 'meta', 'hidden']
- for k in keys:
- if k in o:
- obj_to_save[k] = o[k]
-
- obj_to_save['provenance'] = prov_to_save
- objs_to_save.append(obj_to_save)
-
ws = Workspace(self.ws_url, token=ctx['token'])
- try:
- info = ws.save_objects({'id': wsid, 'objects': objs_to_save})
- except WorkspaceError as e:
- self.log('Logging workspace error on save_objects: {}\n{}'.format(
- e.message, e.data))
- raise
+ prov = ctx.provenance()
+ info = save_objects(ws, params, prov)
#END save_objects
# At some point might do deeper type checking...
@@ -1460,7 +1422,7 @@ def get_objects(self, ctx, params):
try:
retobjs = ws.get_objects2(input_)['data']
except WorkspaceError as e:
- self.log('Logging workspace error on get_objects: {}\n{}'.format(
+ log('Logging workspace error on get_objects: {}\n{}'.format(
e.message, e.data))
raise
results = []
@@ -1473,7 +1435,7 @@ def get_objects(self, ctx, params):
hs = 'handle_stacktrace'
if he in o or hs in o:
ref = self.make_ref(o['info'])
- self.log('Handle error for object {}: {}.\nStacktrace: {}'
+ log('Handle error for object {}: {}.\nStacktrace: {}'
.format(ref, o.get(he), o.get(hs)))
if ignore_err:
res = None
@@ -1545,10 +1507,10 @@ def download_staging_file(self, ctx, params):
staging_file_name = os.path.basename(staging_file_subdir_path)
staging_file_path = self._get_staging_file_path(ctx['user_id'], staging_file_subdir_path)
- self.log('Start downloading staging file: %s' % staging_file_path)
+ log('Start downloading staging file: %s' % staging_file_path)
shutil.copy2(staging_file_path, self.tmp)
copy_file_path = os.path.join(self.tmp, staging_file_name)
- self.log('Copied staging file from %s to %s' %
+ log('Copied staging file from %s to %s' %
(staging_file_path, copy_file_path))
copy_file_path = self._unpack(copy_file_path, True)
@@ -1587,7 +1549,7 @@ def download_web_file(self, ctx, params):
file_url = params.get('file_url')
download_type = params.get('download_type')
- self.log('Start downloading web file from: {}'.format(file_url))
+ log('Start downloading web file from: {}'.format(file_url))
copy_file_path = self._download_file(download_type, file_url)
results = {'copy_file_path': copy_file_path}
diff --git a/lib/DataFileUtil/implementation.py b/lib/DataFileUtil/implementation.py
new file mode 100644
index 0000000..4936dee
--- /dev/null
+++ b/lib/DataFileUtil/implementation.py
@@ -0,0 +1,83 @@
+# contains implementations for DFU methods. This allows for unit testing.
+
+# hmm, class or functions, class or functions... let's go with functions for now.
+# If we wind up having to pass in a ton of crap every time try an OO approach.
+
+# TODO move more method implementations here - or in other files - as needed.
+# TODO mypy this sucker up
+
+import copy
+import time
+
+from installed_clients.baseclient import ServerError as WorkspaceError
+
+
+def log(message, prefix_newline=False):
+ print(('\n' if prefix_newline else '') + str(time.time()) + ': ' + str(message))
+
+# Copies of this in AssemblyUtil and GenomeFileUtil may be redundant since we're sorting here
+# Note that insertion order is only maintained since python 3.6 and is only guaranteed since 3.7
+# In 3.6 it was an implementation detail.
+# As of 2020/12/12 Python 3.6 is provided in the kbase/sdkbase2 image
+def _sort_dict(in_struct):
+ """
+ Recursively sort a dictionary by dictionary keys.
+ """
+ if isinstance(in_struct, dict):
+ return {k: _sort_dict(in_struct[k]) for k in sorted(in_struct)}
+ elif isinstance(in_struct, list):
+ return [_sort_dict(k) for k in in_struct]
+ else:
+ return in_struct
+
+
+def save_objects(ws, params, prov):
+ # TODO unit tests
+ objs = params.get('objects')
+ if not objs:
+ raise ValueError('Required parameter objects missing')
+ wsid = params.get('id')
+ if not wsid:
+ raise ValueError('Required parameter id missing')
+ objs_to_save = []
+ for o in objs:
+ obj_to_save = {}
+
+ prov_to_save = prov
+ if 'extra_provenance_input_refs' in o:
+ # need to make a copy so we don't clobber other objects
+ prov_to_save = copy.deepcopy(prov)
+ extra_input_refs = o['extra_provenance_input_refs']
+ if extra_input_refs:
+ if len(prov) > 0:
+ if 'input_ws_objects' in prov[0]:
+ prov_to_save[0]['input_ws_objects'].extend(extra_input_refs)
+ else:
+ prov_to_save[0]['input_ws_objects'] = extra_input_refs
+ else:
+ prov_to_save = [{'input_ws_objects': extra_input_refs}]
+
+ keys = ['type', 'name', 'objid', 'meta', 'hidden']
+ for k in keys:
+ if k in o:
+ obj_to_save[k] = o[k]
+ """
+ Sorting the data is important for 2 reasons:
+ 1) It prevents the workspace from rejecting the save because the sort takes too much memory.
+ The workspace puts limits on memory use because it has to service many apps / UIs / etc.
+ at once.
+ 2) It distributes the sort across the app worker nodes rather than concentrating them on
+ the workspace node.
+ """
+ # TODO sort in WSLargeDataIO as well
+ if 'data' in o:
+ obj_to_save['data'] = _sort_dict(o['data'])
+
+ obj_to_save['provenance'] = prov_to_save
+ objs_to_save.append(obj_to_save)
+
+ try:
+ return ws.save_objects({'id': wsid, 'objects': objs_to_save})
+ except WorkspaceError as e:
+ log('Logging workspace error on save_objects: {}\n{}'.format(e.message, e.data))
+ raise
diff --git a/test/implementation_test.py b/test/implementation_test.py
new file mode 100644
index 0000000..78a482c
--- /dev/null
+++ b/test/implementation_test.py
@@ -0,0 +1,149 @@
+# unit tests for the implementation.py file.
+
+import json
+
+from unittest.mock import create_autospec
+
+from installed_clients.WorkspaceClient import Workspace
+
+from DataFileUtil.implementation import save_objects
+
+# TODO add more save_object unit tests.
+# TODO upgrade to pytest.
+# TODO figure out why the test results are interleaved with test logs & fix
+# TODO figure out why there appear to be 2 test runs, 1 with this file, 1 without, per kb-sdk test
+# TODO set up a makefile target to run only unit tests
+
+def test_save_objects_sorted():
+ print("***** test_save_objects_sorted ****")
+ ws = create_autospec(Workspace, spec_set=True, instance=True)
+
+ ws.save_objects.return_value = [
+ [
+ 17,
+ 'objname',
+ 'Some.Type-2.4',
+ '2020-12-12T19:52:29+0000',
+ 2367,
+ 'username',
+ 49778,
+ 'MyWorkspace',
+ '99914b932bd37a50b983c5e7c90ae93b',
+ 2,
+ {}],
+ [
+ 18,
+ 'objname2',
+ 'Other.Type-2.4',
+ '2020-12-12T19:52:29+0000',
+ 1,
+ 'username',
+ 49778,
+ 'MyWorkspace',
+ '99914b932bd37a50b983c5e7c90ae93b',
+ 2,
+ {}]
+ ]
+
+ params = {
+ 'id': 49778,
+ 'objects': [
+ {
+ 'type': 'Some.Type-2.4',
+ 'name': 'objname',
+ 'data': {'sorted': [
+ 3,
+ 2,
+ 1,
+ {
+ '4': 'a',
+ '3': 'a',
+ '1': 'a',
+ '2': 'a'
+ }],
+ 'by': 1,
+ 'yoda': ['whoo', 'whee', {'b': 1, 'a': 2}],
+ 'this was': 'foo'}
+ },
+ {
+ 'type': 'Other.Type-2.4',
+ 'name': 'objname2',
+ 'data': {
+ 'a': 1,
+ 'c': 2,
+ 'b': 3,
+ }
+ }]
+ }
+
+ res = save_objects(ws, params, {})
+ expected = [
+ [
+ 17,
+ 'objname',
+ 'Some.Type-2.4',
+ '2020-12-12T19:52:29+0000',
+ 2367,
+ 'username',
+ 49778,
+ 'MyWorkspace',
+ '99914b932bd37a50b983c5e7c90ae93b',
+ 2,
+ {}],
+ [
+ 18,
+ 'objname2',
+ 'Other.Type-2.4',
+ '2020-12-12T19:52:29+0000',
+ 1,
+ 'username',
+ 49778,
+ 'MyWorkspace',
+ '99914b932bd37a50b983c5e7c90ae93b',
+ 2,
+ {}]
+ ]
+ assert res == expected
+
+ ws.save_objects.assert_called_once_with({
+ 'id': 49778,
+ 'objects': [
+ {
+ 'type': 'Some.Type-2.4',
+ 'name': 'objname',
+ 'data': {'sorted': [
+ 3,
+ 2,
+ 1,
+ {
+ '4': 'a',
+ '3': 'a',
+ '1': 'a',
+ '2': 'a'
+ }],
+ 'by': 1,
+ 'yoda': ['whoo', 'whee', {'b': 1, 'a': 2}],
+ 'this was': 'foo'
+ },
+ 'provenance': {}
+ },
+ {
+ 'type': 'Other.Type-2.4',
+ 'name': 'objname2',
+ 'data': {
+ 'a': 1,
+ 'c': 2,
+ 'b': 3,
+ },
+ 'provenance': {}
+ }]
+ })
+
+ assert json.dumps(ws.save_objects.call_args[0][0]['objects'][0]['data']) == (
+ '{"by": 1, "sorted": [3, 2, 1, {"1": "a", "2": "a", "3": "a", "4": "a"}], ' +
+ '"this was": "foo", "yoda": ["whoo", "whee", {"a": 2, "b": 1}]}'
+ )
+
+ assert json.dumps(ws.save_objects.call_args[0][0]['objects'][1]['data']) == (
+ '{"a": 1, "b": 3, "c": 2}'
+ )