function entity = getCurrentEntity(fieldName, fcnName)
%getCurrentEntity Common implementation for getCurrentJob/Task/Worker/Cluster.
%   entity = getCurrentEntity(fieldName, fcnName) extracts the field named
%   fieldName from the distcomp "object root". fcnName is the name of the
%   function that the user originally invoked and is used for the
%   thread-worker error message.
%
%   On a process-worker, returns the current parallel.<entity>.
%
%   On a thread worker, throws an error saying the entity cannot be accessed.
%
%   On a client, returns [].

% Copyright 2020-2021 The MathWorks, Inc.

if parallel.internal.pool.isPoolThreadWorker()
    throwAsCaller(MException(message(...
        'parallel:lang:pool:DisallowedParallelFeature', fcnName)));
end

if ~system_dependent('isdmlworker')
    % Short-circuit for clients.
    entity = [];
    return
end

try
    root = distcomp.getdistcompobjectroot;
    entity = root.(fieldName);
catch E
    warning(E.identifier, '%s', E.message);
    entity = [];
end
end

