# File lib/chef_zero/endpoints/environment_cookbook_versions_endpoint.rb, line 57
      def depsolve(request, unsolved, desired_versions, environment_constraints)
        desired_versions.each do |cb, ver|
          if ver.empty?
            @last_constraint_failure = cb
            return nil
          end
        end

        # If everything is already
        solve_for = unsolved[0]
        return desired_versions if !solve_for

        # Go through each desired version of this cookbook, starting with the latest,
        # until we find one we can solve successfully with
        sort_versions(desired_versions[solve_for]).each do |desired_version|
          new_desired_versions = desired_versions.clone
          new_desired_versions[solve_for] = [ desired_version ]
          new_unsolved = unsolved[1..-1]

          # Pick this cookbook, and add dependencies
          cookbook_obj = FFI_Yajl::Parser.parse(get_data(request, request.rest_path[0..1] + ['cookbooks', solve_for, desired_version]), :create_additions => false)
          cookbook_metadata = cookbook_obj['metadata'] || {}
          cookbook_dependencies = cookbook_metadata['dependencies'] || {}
          dep_not_found = false
          cookbook_dependencies.each_pair do |dep_name, dep_constraint|
            # If the dep is not already in the list, add it to the list to solve
            # and bring in all environment-allowed cookbook versions to desired_versions
            if !new_desired_versions.has_key?(dep_name)
              new_unsolved = new_unsolved + [dep_name]
              # If the dep is missing, we will try other versions of the cookbook that might not have the bad dep.
              if !exists_data_dir?(request, request.rest_path[0..1] + ['cookbooks', dep_name])
                @last_missing_dep = dep_name.to_s
                dep_not_found = true
                break
              end
              new_desired_versions[dep_name] = list_data(request, request.rest_path[0..1] + ['cookbooks', dep_name])
              new_desired_versions = filter_by_constraint(new_desired_versions, dep_name, environment_constraints[dep_name])
            end
            new_desired_versions = filter_by_constraint(new_desired_versions, dep_name, dep_constraint)
          end

          next if dep_not_found

          # Depsolve children with this desired version!  First solution wins.
          result = depsolve(request, new_unsolved, new_desired_versions, environment_constraints)
          return result if result
        end
        return nil
      end