Skip to content

Race condition in popScopesTill #369

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

Closed
svsk417 opened this issue Aug 9, 2024 · 12 comments
Closed

Race condition in popScopesTill #369

svsk417 opened this issue Aug 9, 2024 · 12 comments

Comments

@svsk417
Copy link

svsk417 commented Aug 9, 2024

Hello there!
I just observed a race condition in popScopesTillFunction when executed multiple times within the same async execution block (is it called this way?) of the run loop.
My scenario is, that I want to pop four scopes at once and the scopes are pushed as follows from inner to outer:

  • ScopeA
  • ScopeB
  • ScopeC
  • ScopeD

In my implementation I make sure that I pop the scopes from outer to inner - at least I call the async functions in the following order, but in different places. As such they might all get to poppedScopeName = _currentScope.name; in the implementation of the package. If now popScopesTill(ScopeA); discards a scope that the other popScopesTill should discard and the other popScopesTill does find its target scope to pop, the scopes will be popped until the root scope is reached the application will crash:

popScopesTill(ScopeD);
popScopesTill(ScopeC);
popScopesTill(ScopeB);
popScopesTill(ScopeA);

Current implementation:

  @override
  Future<bool> popScopesTill(String scopeName, {bool inclusive = true}) async {
    assert(
      scopeName != _baseScopeName || !inclusive,
      "You can't pop the base scope",
    );
    if (_scopes.firstWhereOrNull((x) => x.name == scopeName) == null) {
      return false;
    }
    String? poppedScopeName;
    do {
      poppedScopeName = _currentScope.name;
      await popScope();
    } while (inclusive
        ? (poppedScopeName != scopeName)
        : (_currentScope.name != scopeName));
    onScopeChanged?.call(false);
    return true;
  }

This could be prevented using the synchronized package and locking this function. What do you think about this solution?
Thank you for your time to maintain this package! We are really grateful for it! If I can support you with the implementation, just post me!

Implementation details of the way scoppes are pushed and popped
import 'package:blocs/blocs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'di.dart';

class DiScopeWidget extends StatelessWidget {
  final List<DiScope> diScopes;
  final Widget child;
  final Widget? loadingWidget;

  DiScopeWidget({
    required DiScope diScope,
    required this.child,
    this.loadingWidget,
    super.key,
  }) : diScopes = [diScope];

  DiScopeWidget.multipleScopes({
    required this.diScopes,
    required this.child,
    this.loadingWidget,
    super.key,
  }) : assert(diScopes.isNotEmpty);

  @override
  Widget build(BuildContext context) {
    final List<Widget> blocProviders = [];
    for (final (index, diScope) in diScopes.reversed.indexed) {
      // this is the inner bloc provider
      if (index == 0) {
        blocProviders.add(
          Builder(
            key: ValueKey('${diScope.toString()}_Builder'),
            builder: (context) {
              return BlocProvider(
                key: ValueKey('${diScope.toString()}_BlocProvider'),
                create: (context) => getIt<DiScopeCubit>(
                  param1: diScope,
                ),
                child: BlocBuilder<DiScopeCubit, DiScopeState>(
                  key: ValueKey('${diScope.toString()}_BlocBuilder'),
                  builder: (context, state) {
                    return state.when(
                      loading: () => loadingWidget ?? Container(),
                      ready: () => child,
                    );
                  },
                ),
              );
            },
          ),
        );
        continue;
      }
      blocProviders.add(
        Builder(
          key: ValueKey('${diScope.toString()}_Builder'),
          builder: (context) {
            return BlocProvider(
              key: ValueKey('${diScope.toString()}_BlocProvider'),
              create: (context) => getIt<DiScopeCubit>(
                param1: diScope,
              ),
              child: BlocBuilder<DiScopeCubit, DiScopeState>(
                key: ValueKey('${diScope.toString()}_BlocBuilder'),
                builder: (context, state) {
                  return state.when(
                    loading: () => loadingWidget ?? Container(),
                    ready: () => blocProviders[index - 1],
                  );
                },
              ),
            );
          },
        ),
      );
    }
    return blocProviders.last;
  }
}

class DiScopeCubit extends Cubit<DiScopeState> {
  final DiScope _diScope;
  final ScopesHandler _scopesHandler;

  DiScopeCubit({
    required DiScope diScope,
    required ScopesHandler scopesHandler,
  })  : _diScope = diScope,
        _scopesHandler = scopesHandler,
        super(const DiScopeState.loading()) {
    switch (diScope) {
        // push scopes
        .then(() => emit(DiScopeState.ready()));
    }
  }

  @override
  Future<void> close() async {
    switch (_diScope) {
        // popScopesUntil the specified scope
    }
    await super.close();
  }
}
@svsk417
Copy link
Author

svsk417 commented Aug 9, 2024

Relates to #364

@escamoteur
Copy link
Collaborator

escamoteur commented Aug 9, 2024 via email

@svsk417
Copy link
Author

svsk417 commented Aug 9, 2024

Yes, I checked it. Happens also there. Thank you for looking into it.
I guess I can use dropScope in my case as well, but just wanted to notify you that there is an issue. So, it is not that urgent.

@escamoteur
Copy link
Collaborator

escamoteur commented Aug 11, 2024 via email

@svsk417
Copy link
Author

svsk417 commented Aug 12, 2024

grafik
Yes, if you take a look at the image and use the code that I have provided in 'Implementation details of the way scoppes are pushed and popped', the widgets will be discarded in the following order, if the user logs out:

  1. Payment -> PaymentScope
  2. Cart -> Nothing
  3. ShoppingOverview -> CartScope & LoggedInScope

IMO this could be a valid case
Yes, I would lock it and wait for the scope to be popped. But the issue I see in here, would be that resolution of a dependency after/while the scope is popped might yield a service that is about to be disposed. Therefore, the lock would need to be a read/write lock, instead of just an exclusive access (write -> locking other write & read ops) and read (only locking write ops while reading). But this might be not that advisable, since not every resolution is async. 🤔 Maybe that is Ok, since we are not operating in an environment where every loop needs to be verified. Was just thinking about it. Thank you for looking into this!

@escamoteur
Copy link
Collaborator

escamoteur commented Aug 12, 2024 via email

@escamoteur
Copy link
Collaborator

escamoteur commented Aug 12, 2024 via email

@svsk417
Copy link
Author

svsk417 commented Aug 12, 2024

I have not, yet. Thanks for the suggestion!
Write use case would be

  1. Preventing that dependencies are registered while a scope is being popped (if not done prevented yet!?)
  2. Preventing the original issue with popScopeTil
  3. Preventing that dependencies are resolved while a "popping process" is executing (if not done prevented yet!?)

@escamoteur
Copy link
Collaborator

escamoteur commented Aug 12, 2024 via email

@escamoteur
Copy link
Collaborator

escamoteur commented Aug 12, 2024 via email

@escamoteur
Copy link
Collaborator

Pleast test 8.0.0-pre-7 if you still ahve that problem

@svsk417
Copy link
Author

svsk417 commented Aug 15, 2024

I just tested it. It seems to work with 8.0.0-pre-7.
Thanks for the effort!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants