Skip to content

Commit

Permalink
adding the new status of sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
ABTastyAdel committed Jul 11, 2024
1 parent bfb39e1 commit 8312812
Show file tree
Hide file tree
Showing 13 changed files with 95 additions and 61 deletions.
22 changes: 6 additions & 16 deletions example/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,6 @@ PODS:
- device_information (0.0.1):
- Flutter
- Flutter (1.0.0)
- FMDB (2.7.12):
- FMDB/standard (= 2.7.12)
- FMDB/Core (2.7.12)
- FMDB/standard (2.7.12):
- FMDB/Core
- path_provider_foundation (0.0.1):
- Flutter
- FlutterMacOS
Expand All @@ -17,19 +12,15 @@ PODS:
- FlutterMacOS
- sqflite (0.0.3):
- Flutter
- FMDB (>= 2.7.5)
- FlutterMacOS

DEPENDENCIES:
- device_info (from `.symlinks/plugins/device_info/ios`)
- device_information (from `.symlinks/plugins/device_information/ios`)
- Flutter (from `Flutter`)
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
- sqflite (from `.symlinks/plugins/sqflite/ios`)

SPEC REPOS:
trunk:
- FMDB
- sqflite (from `.symlinks/plugins/sqflite/darwin`)

EXTERNAL SOURCES:
device_info:
Expand All @@ -43,16 +34,15 @@ EXTERNAL SOURCES:
shared_preferences_foundation:
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
sqflite:
:path: ".symlinks/plugins/sqflite/ios"
:path: ".symlinks/plugins/sqflite/darwin"

SPEC CHECKSUMS:
device_info: d7d233b645a32c40dfdc212de5cf646ca482f175
device_information: d652f6dcea86bdc5300ffd495486de1d5047bf4f
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
FMDB: 728731dd336af3936ce00f91d9d8495f5718a0e6
path_provider_foundation: eaf5b3e458fc0e5fbb9940fb09980e853fe058b8
shared_preferences_foundation: e2dae3258e06f44cc55f49d42024fd8dd03c590c
sqflite: 31f7eba61e3074736dff8807a9b41581e4f7f15a
path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78
sqflite: 673a0e54cc04b7d6dba8d24fb8095b31c3a99eec

PODFILE CHECKSUM: ce13d36744da294d67f8e460dbb7aed7c09bd7f4

Expand Down
2 changes: 1 addition & 1 deletion example/lib/Providers/fs_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class FSData extends ChangeNotifier {
// Apikey
String _apiKey = "DxAcxlnRB9yFBZYtLDue1q01dcXZCw6aM49CQB23"; //
// EnvId
String _envId = "bkk9glocmjcg0vtmdlng"; //
String _envId = "bkk9glocmjcg0vtmdlng"; // cpg6t44kv21g1ajm3bhg
// Mode
Mode _mode = Mode.DECISION_API;
// Timeout
Expand Down
4 changes: 3 additions & 1 deletion example/lib/widgets/configuration.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class _ConfigurationState extends State<Configuration> with ShowDialog {
FlagshipConfig config = ConfigBuilder()
.withLogLevel(Level.ALL)
.withMode(fsData.sdkMode)
.withStatusListener((newStatus) {
.onSdkStatusChanged((newStatus) {
print('--------- Callback with $newStatus ---------');
//var newVisitor;
if (newStatus == FSSdkStatus.SDK_INITIALIZED) {
Expand Down Expand Up @@ -115,6 +115,8 @@ class _ConfigurationState extends State<Configuration> with ShowDialog {

// Fetch flags
_fetchFalgs() {
var st = Flagship.getStatus();
print(" @@@@@@@@@@ Status before fetching is $st @@@@@@@@@@@@@@@@ ");
var titleMsg = '';
Flagship.getCurrentVisitor()?.fetchFlags().whenComplete(() {
switch (Flagship.getStatus()) {
Expand Down
9 changes: 0 additions & 9 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -492,14 +492,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.5.1"
win32:
dependency: transitive
description:
name: win32
sha256: "1414f27dd781737e51afa9711f2ac2ace6ab4498ee98e20863fa5505aa00c58c"
url: "https://pub.dev"
source: hosted
version: "5.0.4"
xdg_directories:
dependency: transitive
description:
Expand All @@ -511,4 +503,3 @@ packages:
sdks:
dart: ">=3.4.0 <4.0.0"
flutter: ">=3.22.0"

64 changes: 53 additions & 11 deletions lib/decision/bucketing_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'package:flagship/flagship.dart';
import 'package:flagship/flagship_config.dart';
import 'package:flagship/model/bucketing.dart';
import 'package:flagship/model/campaigns.dart';
import 'package:flagship/status.dart';
import 'package:flagship/utils/logger/log_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
Expand All @@ -23,9 +24,9 @@ class BucketingManager extends DecisionManager {

Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

String lastModfiedKey = "FSLastModifiedScript";
String lastModfiedKey = "FSLastModifiedScript_%s";
String bucketingFolder = "/flagship_bucketing/";
String fileName = "bucketing.json";
String fileName = "bucketing_%s.json";

DataUsageTracking? bkDataUsage;

Expand Down Expand Up @@ -54,7 +55,7 @@ class BucketingManager extends DecisionManager {
}
}

_downloadScript() async {
Future<Bucketing?> _downloadScript() async {
SharedPreferences prefs = await _prefs;
// Create url
String urlString = Endpoints.BUCKETING_SCRIPT
Expand All @@ -63,7 +64,11 @@ class BucketingManager extends DecisionManager {
var response = await this.service.sendHttpRequest(
RequestType.Get,
urlString,
{"if-modified-since": prefs.getString(lastModfiedKey) ?? ""},
{
"if-modified-since": prefs.getString(lastModfiedKey.replaceFirst(
"%s", Flagship.sharedInstance().envId.toString())) ??
""
},
null,
timeoutMs:
Flagship.sharedInstance().getConfiguration()?.timeout ?? TIMEOUT);
Expand All @@ -72,19 +77,22 @@ class BucketingManager extends DecisionManager {
Flagship.logger(Level.ALL, response.body, isJsonString: true);
String? lastModified = response.headers["last-modified"];
if (lastModified != null) {
prefs.setString(lastModfiedKey, lastModified);
prefs.setString(
lastModfiedKey.replaceFirst(
"%s", Flagship.sharedInstance().envId.toString()),
lastModified);
}
// Save response body
_saveFile(response.body);

// Report TR
DataUsageTracking.sharedInstance().processTroubleShootingHttp(
CriticalPoints.SDK_BUCKETING_FILE.name, response);
break;
// Update sdk status
return Bucketing.fromJson(json.decode(response.body));
case 304:
Flagship.logger(Level.ALL,
"The bucketing script is not modified since last download");
break;
return null;
default:
// Report Troubleshooting
DataUsageTracking.sharedInstance().processTroubleShootingHttp(
Expand All @@ -98,7 +106,7 @@ class BucketingManager extends DecisionManager {
void startPolling() {
// Create and launch the polling process here...
this.polling = Polling(intervalPolling, () async {
await _downloadScript();
await _downloadScript().then(((bk) => {_updateStatus(bk)}));
});
this.polling?.start();
}
Expand All @@ -115,14 +123,20 @@ class BucketingManager extends DecisionManager {
throw Exception('Flagship, Failed to save file');
});
// We got the path to save the json file
File jsonFile = File(bucketingDirectory.path + fileName);

File jsonFile = File(bucketingDirectory.path +
fileName.replaceFirst(
"%s", Flagship.sharedInstance().envId.toString()));
jsonFile.writeAsString(body);
}

// Read the saved file
Future<String?> _readFile() async {
final directory = await getApplicationDocumentsDirectory();
File jsonFile = File(directory.path + bucketingFolder + fileName);
File jsonFile = File(directory.path +
bucketingFolder +
fileName.replaceFirst(
"%s", Flagship.sharedInstance().envId.toString()));
if (jsonFile.existsSync() == true) {
return jsonFile.readAsStringSync();
} else {
Expand All @@ -138,4 +152,32 @@ class BucketingManager extends DecisionManager {
this.assignationHistory?.addEntries(newAssign.entries);
}
}

// Use tbk_file to refresh the state
void _updateStatus(Bucketing? bk_file) {
if (bk_file != null) {
Flagship.sharedInstance().onUpdateState(
bk_file.panic ? FSSdkStatus.SDK_PANIC : FSSdkStatus.SDK_INITIALIZED);
} else {
_getSavedScript().then((savedBk) {
Flagship.sharedInstance().onUpdateState(savedBk?.panic ?? false
? FSSdkStatus.SDK_PANIC
: FSSdkStatus.SDK_INITIALIZED);
});
}
}

Future<Bucketing?> _getSavedScript() async {
String? jsonString = await _readFile().catchError((error) {
Flagship.logger(Level.ALL,
"Error on reading the saved bucketing or the file doesn't exist");
return null;
});
if (jsonString != null) {
return Bucketing.fromJson(json.decode(jsonString));
} else {
Flagship.logger(Level.ALL, "Flagship, Failed to synchronize");
return null;
}
}
}
9 changes: 6 additions & 3 deletions lib/flagship.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@ class Flagship with FlagshipDelegate {
Flagship._configuration = config;
}
if (_configuration.decisionMode == Mode.BUCKETING) {
_singleton.onUpdateState(FSSdkStatus.SDK_INITIALIZING);

Flagship._configuration.decisionManager.startPolling();
} else {
_singleton.onUpdateState(FSSdkStatus.SDK_INITIALIZED);
}
_singleton.onUpdateState(FSSdkStatus.SDK_INITIALIZED);
Flagship.logger(Level.INFO, STARTED);
} else {
_singleton.onUpdateState(FSSdkStatus.SDK_NOT_INITIALIZED);
Expand Down Expand Up @@ -133,8 +136,8 @@ class Flagship with FlagshipDelegate {

// Trigger the callback
// Check if the callback if not null before trigger it
if (Flagship._configuration.statusListener != null) {
Flagship._configuration.statusListener!(newStatus);
if (Flagship._configuration.onSdkStatusChanged != null) {
Flagship._configuration.onSdkStatusChanged!(newStatus);
}
}

Expand Down
14 changes: 7 additions & 7 deletions lib/flagship_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const TIMEOUT = 2000;
typedef OnVisitorExposed = void Function(
VisitorExposed visitorExposed, ExposedFlag fromFlag)?;

typedef StatusListener = void Function(FSSdkStatus newStatus)?;
typedef SdkStatusChanged = void Function(FSSdkStatus newStatus)?;

@protected
class FlagshipConfig {
Expand All @@ -35,7 +35,7 @@ class FlagshipConfig {
// LogManager
LogManager? logManager;
// Status listner
StatusListener statusListener;
SdkStatusChanged onSdkStatusChanged;
// Callback trigger on flag visitor exposed
OnVisitorExposed onVisitorExposed;

Expand All @@ -55,7 +55,7 @@ class FlagshipConfig {

FlagshipConfig(this.decisionMode, this.timeout, this.pollingTime,
this._logLevel, this.onVisitorExposed, this.trackingManagerConfig,
{this.statusListener,
{this.onSdkStatusChanged,
this.visitorCacheImp,
this.hitCacheImp,
this.disableDeveloperUsageTracking = false}) {
Expand Down Expand Up @@ -96,7 +96,7 @@ class ConfigBuilder {
int _pollingTime = 60;

// StatusListener
StatusListener? _statusListener;
SdkStatusChanged? _onSdkStatusChanged;

// Tracking Config
TrackingManagerConfig? _trackingManagerConfig;
Expand Down Expand Up @@ -138,8 +138,8 @@ class ConfigBuilder {
}

// StatusListener
ConfigBuilder withStatusListener(StatusListener listener) {
_statusListener = listener;
ConfigBuilder onSdkStatusChanged(SdkStatusChanged pSdkStatusChanged) {
_onSdkStatusChanged = pSdkStatusChanged;
return this;
}

Expand Down Expand Up @@ -180,7 +180,7 @@ class ConfigBuilder {
FlagshipConfig build() {
return FlagshipConfig(_mode, _timeout, _pollingTime, _logLevel,
_onVisitorExposed, _trackingManagerConfig ?? TrackingManagerConfig(),
statusListener: _statusListener,
onSdkStatusChanged: _onSdkStatusChanged,
hitCacheImp: _hitCacheImp,
visitorCacheImp: _visitorCacheImp,
disableDeveloperUsageTracking: _disableDeveloperUsageTracking);
Expand Down
9 changes: 5 additions & 4 deletions test/callback_test.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:flagship/decision/api_manager.dart';
import 'package:flagship/flagship.dart';
import 'package:flagship/status.dart';
import 'package:flagship/utils/constants.dart';
import 'package:flagship/utils/logger/log_manager.dart';
import 'package:flutter/widgets.dart';
Expand Down Expand Up @@ -28,7 +29,7 @@ void main() {
FlagshipConfig conf =
ConfigBuilder().withTimeout(4000).withLogLevel(Level.ALL).build();

expect(conf.statusListener, null);
expect(conf.onSdkStatusChanged, null);
expect(conf.timeout, 4000);
expect(conf.decisionMode, Mode.DECISION_API);
});
Expand All @@ -47,16 +48,16 @@ void main() {
});

FlagshipConfig config = ConfigBuilder().withTimeout(TIMEOUT).build();
config.statusListener = (newStatus) {
if (newStatus == Status.PANIC_ON) {
config.onSdkStatusChanged = (newStatus) {
if (newStatus == FSSdkStatus.SDK_PANIC) {
// ignore: deprecated_member_use_from_same_package
expect(Flagship.getCurrentVisitor()?.getModification('key1', 12), 12);
expect(newStatus, Flagship.getStatus());
}
};

config.decisionManager = fakePanicApi;
Flagship.sharedInstance().onUpdateState(Status.NOT_INITIALIZED);
Flagship.sharedInstance().onUpdateState(FSSdkStatus.SDK_NOT_INITIALIZED);
Flagship.start("bkk9glocmjcg0vtmdlrr", "apiKey", config: config);

var v1 = Flagship.newVisitor(visitorId: "visitorId", hasConsented: true)
Expand Down
9 changes: 5 additions & 4 deletions test/default_strategy_test.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:flagship/decision/api_manager.dart';
import 'package:flagship/flagship.dart';
import 'package:flagship/flagship_version.dart';
import 'package:flagship/status.dart';
import 'package:flagship/utils/logger/log_manager.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
Expand Down Expand Up @@ -61,7 +62,7 @@ void main() {
// ignore: deprecated_member_use_from_same_package

await v1.fetchFlags().whenComplete(() {
expect(Flagship.getStatus(), Status.READY);
expect(Flagship.getStatus(), FSSdkStatus.SDK_INITIALIZED);

/// Activate
// ignore: deprecated_member_use_from_same_package
Expand Down Expand Up @@ -127,7 +128,7 @@ void main() {
/// count the callback trigger
FlagshipConfig config =
ConfigBuilder().withTimeout(TIMEOUT).withStatusListener((newStatus) {
ConfigBuilder().withTimeout(TIMEOUT).onSdkStatusChanged((newStatus) {
print(" ---- statusListner is trigger ---- ");
expect(Flagship.getStatus() == newStatus, true);
expect(newStatus, Flagship.getStatus());
Expand All @@ -144,7 +145,7 @@ void main() {

// ignore: deprecated_member_use_from_same_package
await v1.synchronizeModifications().then((value) {
expect(Flagship.getStatus(), Status.READY);
expect(Flagship.getStatus(), FSSdkStatus.SDK_INITIALIZED);
// ignore: deprecated_member_use_from_same_package
// expect(v1.getModification('aliasTer', 'default'), "testValue");
// Test the case when the modificattion is empty
Expand All @@ -170,7 +171,7 @@ void main() {
});

FlagshipConfig config =
ConfigBuilder().withTimeout(TIMEOUT).withStatusListener((newStatus) {
ConfigBuilder().withTimeout(TIMEOUT).onSdkStatusChanged((newStatus) {
print(" ---- statusListner is trigger ---- ");
expect(Flagship.getStatus() == newStatus, true);
expect(newStatus, Flagship.getStatus());
Expand Down
Loading

0 comments on commit 8312812

Please sign in to comment.