Skip to content

[WIP] IServiceProvider on runspace - #17349

Closed
Staffan Gustafsson (powercode) wants to merge 6 commits into
PowerShell:masterfrom
powercode:IServiceProvider
Closed

Staffan Gustafsson (powercode) wants to merge 6 commits into
PowerShell:masterfrom
powercode:IServiceProvider

Conversation

@powercode

Copy link
Copy Markdown
Collaborator

PR Summary

PR Context

PR Checklist

{
get => _sessionState.ExecutionContext.ServiceProvider;
set => _sessionState.ExecutionContext.ServiceProvider = value;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having this API on PSModuleInfo makes it seem like any module can use this to set their own service provider. If two modules try to set up different service providers, then the last loaded will win and the other will break.

Have you considered using a ConditionalWeakTable<PSModuleInfo, IServiceProvider>?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having lower-level modules be able to rebuild a service provider with additional services may be useful.

But perhaps something that should be made more specific?

The use case I want to cover is to be able to set an initial service provider from the InitialSessionState and make it possible to have modules recreate it with some added services.

That could perhaps be abstracted with a get only IServiceProvider property, and some

IServiceProvider ServiceProvider { get;  }
void AddServices(IServiceCollection services)

But in that case, I think we would have to commit to some implementation of IServiceProvider.

@SeeminglyScience Patrick Meinecke (SeeminglyScience) May 16, 2022 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think it'll be potentially challenging for different module authors to use the same instance. Especially if they find themselves in a runspace with a different implementation.

What I was getting at with the weak table suggestion, you could have a common assembly with code like this:

namespace MyOrg
{
    public static class Services
    {
        private static readonly ConditionalWeakTable<Runspace, IServiceProvider> s_services = new();

        [Hidden, EditorBrowsable(EditorBrowsableState.Never)]
        public static void SetInternal(Runspace runspace, IServiceProvider testProvider) => s_services.AddOrUpdate(runspace, testProvider);

        public static IServiceProvider Get(Runspace runspace) => s_services.GetValue(runspace, Create);

        public static IServiceProvider GetFromTLS() => s_services.GetValue(Runspace.DefaultRunspace, Create);

        private static IServiceProvider Create(Runspace key)
        {
            return s_isTesting ? new TestingServiceProvider() : new ServiceProvider();
        }
    }
}

public class Tests
{
    [TestMethod]
    public void CanSearchItem()
    {
        var restClient = new Mock<IJiraRestClient>();
        restClient.Setup(c => c.ExecuteRequestAsync(Method.POST, "rest/api/2/search", It.IsAny<object>(), It.IsAny<CancellationToken>()))
            .Returns(() => Task.FromResult(JToken.Parse(SR.SearchResultABC)))
            .Verifiable();

        var serviceCollection = new ServiceCollection();
        serviceCollection.AddSingleton<IJiraRestClient>(restClient.Object);
        var provider = serviceCollection.BuildServiceProvider();

        var iss = InitialSessionState.CreateDefault2();
        iss.ImportPSModulesFromPath(typeof(SearchJiraIssue).Assembly.Location);
        using var ps = PowerShell.Create(iss);
        Services.SetInternal(ps.Runspace, provider);

        CmdletInfo searchInfo = new CmdletInfo(@"Jira\Search-JiraIssue", typeof(SearchJiraIssue));
        ps.AddCommand(searchInfo);
        ps.AddParameter(nameof(SearchJiraIssue.ProjectKey), "ABC");

        var results = ps.Invoke<Atlassian.Jira.Issue>();

        restClient.Verify();
        // Assert on results
    }
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is quite similar to what I have been using (not with a ConditionalWeakTable, good suggestion!)
but that doesn't really help with injecting something differently in tests, or am I missing something?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated with how I'd handle a different service provider for tests. Could also just go with a static property that's like ServiceProviderOverride.

If that doesn't answer your question, can you provide an example of how you'd use it with the proposal for tests?

@powercode Staffan Gustafsson (powercode) May 16, 2022 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each test registers its own interfaces with the ServiceProvider. That is up to each test, and not the responsibility of the Services class.

So the question for me has been how to propagate the service provider for each test.

A test could look like this:

[TestMethod]
public void CanSearchItem()
{
	var restClient = new Mock<IJiraRestClient>();
	restClient.Setup(c => c.ExecuteRequestAsync(Method.POST, "rest/api/2/search", It.IsAny<object>(), It.IsAny<CancellationToken>()))
		.Returns(() => Task.FromResult(JToken.Parse(SR.SearchResultABC)))
		.Verifiable();

	var serviceCollection = new ServiceCollection();
	serviceCollection.AddSingleton<IJiraRestClient>(restClient.Object);
	var provider = serviceCollection.BuildServiceProvider();
	
	var iss = InitialSessionState.CreateDefault2();
	iss.ImportPSModulesFromPath(typeof(SearchJiraIssue).Assembly.Location);
	iss.ServiceProvider = provider;
	using var ps = PowerShell.Create(iss);

	CmdletInfo searchInfo = new CmdletInfo(@"Jira\Search-JiraIssue", typeof(SearchJiraIssue));
	ps.AddCommand(searchInfo);
	ps.AddParameter(nameof(SearchJiraIssue.ProjectKey), "ABC");

	var results = ps.Invoke<Atlassian.Jira.Issue>();

	restClient.Verify();
	// Assert on results
}		

And the cmdlet could do:

protected override void EndProcessing()
{
	var restClient = SessionState.ServiceProvider?.GetService<IJiraRestClient>() ?? new JiraRestClient();
	var restBody = BuildRestBody();
	var issues = restClient.SearchIssues(restBody);
	foreach (var issue in issues)
	{
		WriteObject(issue);
	}
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is possible to work around this, as you pointed out, with some static map where I could register the runspace mapped to a service provider, but then either all modules would need such a mapping, or share some common library.

By adding this to the SessionState, it seems things become much simpler.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I went ahead and updated my example for that. I agree that it'd be ideal to build in a good way to do DI but I'm not sure what pattern we could use to fit all use cases.

If we go this route, I worry that two separate modules trying to do their own DI will end up stepping on each other. I'd ideally like the service provider to be unique to the module instance, but that doesn't fit your use case either.

I think a common library or module is the easiest solution to this problem without some concept of "module groups" in the engine.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An alternative may be to have SessionState provide a PowerShell defined interface, where there is only a getter for the service provider, and some method like

public interface IServices{
   IServiceProvider ServiceProvider {get;}
   void AddServicesAndRebuildProvider(IServiceCollection services);
}

Then there can only ever be a single ServiceProvider, but you can add services on a per-module basis.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah but I'm thinking if two modules are using a common library and they both register services of the same interface then that'll become an issue still

@pull-request-quantifier-deprecated

Copy link
Copy Markdown

This PR has 9 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra Small
Size       : +8 -1
Percentile : 3.6%

Total files changed: 3

Change summary by file extension:
.cs : +8 -1

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detetcted.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

@daxian-dbw
Dongbo Wang (daxian-dbw) marked this pull request as draft May 16, 2022 17:27
@ghost ghost added the Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept label May 20, 2022
@ghost ghost added the Stale label Jun 4, 2022
@ghost

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 15 days. It will be closed if no further activity occurs within 10 days of this comment.

@ghost ghost closed this Jun 14, 2022
@powercode
Staffan Gustafsson (powercode) deleted the IServiceProvider branch June 16, 2022 21:10
This pull request was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Extra Small Stale Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants