├── .gitattributes
├── .github
└── workflows
│ ├── android.yml
│ ├── ios.yml
│ ├── publishing-android.yml
│ ├── publishing-ios.yml
│ └── rust.yml
├── .gitignore
├── .gitmodules
├── .rusty-hook.toml
├── Cargo.lock
├── Cargo.toml
├── LICENSE
├── Makefile
├── README.md
├── examples
├── .gitignore
├── demo-android
│ ├── .gitignore
│ ├── app
│ │ ├── .gitignore
│ │ ├── build.gradle
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ ├── androidTest
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── featureprobe
│ │ │ │ └── demoandroid
│ │ │ │ └── ExampleInstrumentedTest.kt
│ │ │ ├── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── featureprobe
│ │ │ │ │ └── demoandroid
│ │ │ │ │ ├── FirstFragment.kt
│ │ │ │ │ ├── MainActivity.kt
│ │ │ │ │ └── SecondFragment.kt
│ │ │ └── res
│ │ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ │ ├── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ │ │ ├── layout
│ │ │ │ ├── activity_main.xml
│ │ │ │ ├── content_main.xml
│ │ │ │ ├── fragment_first.xml
│ │ │ │ └── fragment_second.xml
│ │ │ │ ├── menu
│ │ │ │ └── menu_main.xml
│ │ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── navigation
│ │ │ │ └── nav_graph.xml
│ │ │ │ ├── values-land
│ │ │ │ └── dimens.xml
│ │ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ │ ├── values-w1240dp
│ │ │ │ └── dimens.xml
│ │ │ │ ├── values-w600dp
│ │ │ │ └── dimens.xml
│ │ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── themes.xml
│ │ │ │ └── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ ├── data_extraction_rules.xml
│ │ │ │ └── network_security.xml
│ │ │ └── test
│ │ │ └── java
│ │ │ └── com
│ │ │ └── featureprobe
│ │ │ └── demoandroid
│ │ │ └── ExampleUnitTest.kt
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── demo-cmd
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ │ └── main.rs
├── demo-cocoapods
│ ├── Demo.xcodeproj
│ │ └── project.pbxproj
│ ├── Demo
│ │ ├── AppDelegate.swift
│ │ ├── Assets.xcassets
│ │ │ └── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ ├── Base.lproj
│ │ │ ├── LaunchScreen.storyboard
│ │ │ └── Main.storyboard
│ │ ├── Info.plist
│ │ └── ViewController.swift
│ └── Podfile
├── demo-objc
│ ├── Demo.xcodeproj
│ │ └── project.pbxproj
│ ├── Demo
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.m
│ │ ├── Assets.xcassets
│ │ │ ├── AccentColor.colorset
│ │ │ │ └── Contents.json
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Base.lproj
│ │ │ ├── LaunchScreen.storyboard
│ │ │ └── Main.storyboard
│ │ ├── Info.plist
│ │ ├── SceneDelegate.h
│ │ ├── SceneDelegate.m
│ │ ├── ViewController.h
│ │ ├── ViewController.m
│ │ └── main.m
│ └── Podfile
└── demo-swiftpm
│ ├── .gitignore
│ ├── Demo.xcodeproj
│ └── project.pbxproj
│ └── Demo
│ ├── AppDelegate.swift
│ ├── Assets.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
│ ├── Base.lproj
│ ├── LaunchScreen.storyboard
│ └── Main.storyboard
│ ├── Info.plist
│ └── ViewController.swift
├── rust-core
├── Cargo.toml
├── benches
│ └── bench.rs
├── build.rs
├── resources
│ ├── fixtures
│ │ ├── repo.json
│ │ └── toggles.json
│ └── jna.jar
├── src
│ ├── feature_probe.rs
│ ├── lib.rs
│ ├── sync.rs
│ └── user.rs
└── tests
│ └── integration_test.rs
├── rust-toolchain.toml
├── rust-uniffi
├── Cargo.toml
├── build.rs
├── src
│ ├── featureprobe.udl
│ └── lib.rs
├── tests
│ ├── bindings
│ │ ├── test.kts
│ │ └── test.swift
│ └── test_generated_bindings.rs
└── uniffi.toml
├── sdk-android
├── .gitignore
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── publish_aar.gradle
├── sdk
│ ├── .gitignore
│ ├── build.gradle
│ ├── consumer-rules.pro
│ ├── proguard-rules.pro
│ ├── secring.gpg
│ └── src
│ │ ├── androidTest
│ │ └── java
│ │ │ └── com
│ │ │ └── featureprobe
│ │ │ └── sdk
│ │ │ └── ExampleInstrumentedTest.kt
│ │ ├── main
│ │ └── AndroidManifest.xml
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── featureprobe
│ │ └── sdk
│ │ └── ExampleUnitTest.kt
└── settings.gradle
└── sdk-ios
├── .gitignore
├── FeatureProbe.podspec
├── Info.plist
├── LICENSE
├── ObjcFeatureProbe.swift
├── Package.swift
├── README.md
├── build-xcframework.sh
└── module.modulemap
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.swift linguist-detectable=false
2 | *.kt linguist-detectable=false
--------------------------------------------------------------------------------
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | name: Android
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v3
19 | - uses: fwilhe2/setup-kotlin@main
20 | with:
21 | version: 1.6.21
22 | - uses: actions/setup-java@v3
23 | with:
24 | distribution: 'temurin'
25 | java-version: '11'
26 | - uses: maxim-lobanov/setup-android-tools@v1
27 | with:
28 | packages: |
29 | ndk;21.3.6528147
30 | platforms;android-32
31 | - uses: raftario/setup-rust-action@v1
32 | with:
33 | rust-channel: nightly
34 | - name: Run build
35 | run: make build_android
36 | - name: Run tests
37 | run: CLASSPATH="`pwd`/rust-core/resources/jna.jar:$CLASSPATH" cargo test --package fp-mobile-uniffi uniffi_foreign_language_testcase_test_kts
38 |
--------------------------------------------------------------------------------
/.github/workflows/ios.yml:
--------------------------------------------------------------------------------
1 | name: iOS
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: macos-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v3
19 | with:
20 | submodules: recursive
21 | - uses: raftario/setup-rust-action@v1
22 | with:
23 | rust-channel: nightly
24 | - uses: maxim-lobanov/setup-xcode@v1
25 | with:
26 | xcode-version: '13.2.1'
27 | - name: which swift
28 | run: which swift
29 | - name: Run tests
30 | run: cargo test --package fp-mobile-uniffi uniffi_foreign_language_testcase_test_swift
31 | - name: Run build
32 | run: make build_ios
33 |
--------------------------------------------------------------------------------
/.github/workflows/publishing-android.yml:
--------------------------------------------------------------------------------
1 | name: Android Publishing
2 |
3 | on:
4 | push:
5 | tags: [ "*" ]
6 |
7 | env:
8 | CARGO_TERM_COLOR: always
9 |
10 | jobs:
11 | build:
12 |
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v3
17 | - uses: fwilhe2/setup-kotlin@main
18 | with:
19 | version: 1.6.21
20 | - uses: actions/setup-java@v3
21 | with:
22 | distribution: 'temurin'
23 | java-version: '11'
24 | - uses: maxim-lobanov/setup-android-tools@v1
25 | with:
26 | packages: |
27 | ndk;21.3.6528147
28 | platforms;android-32
29 | - uses: raftario/setup-rust-action@v1
30 | with:
31 | rust-channel: nightly
32 | - name: Run build
33 | run: make build_android
34 | - name: Publishing
35 | run: cd sdk-android && ./gradlew sdk:publishReleasePublicationToClient-sdk-mobileRepository -DSIGN_KEYID=${{ secrets.SIGN_KEYID }} -DSIGN_PASSWORD=${{ secrets.SIGN_PASSWORD }} -DOSSRH_USERNAME=${{ secrets.OSSRH_USERNAME }} -DOSSRH_PASSWORD=${{ secrets.OSSRH_PASSWORD }}
36 |
--------------------------------------------------------------------------------
/.github/workflows/publishing-ios.yml:
--------------------------------------------------------------------------------
1 | name: iOS Publishing
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 | tags: [ "*" ]
7 |
8 | env:
9 | CARGO_TERM_COLOR: always
10 |
11 | jobs:
12 | build:
13 |
14 | runs-on: macos-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v3
18 | with:
19 | submodules: recursive
20 | - uses: raftario/setup-rust-action@v1
21 | with:
22 | rust-channel: nightly
23 | - uses: maxim-lobanov/setup-xcode@v1
24 | with:
25 | xcode-version: '13.2.1'
26 | - name: which swift
27 | run: which swift
28 | - name: Run tests
29 | run: cargo test --package fp-mobile-uniffi uniffi_foreign_language_testcase_test_swift
30 | - name: Run build
31 | run: make build_ios
32 |
33 | - name: release ios
34 | uses: EndBug/add-and-commit@v9.1.0
35 | with:
36 | message: 'Bump new version'
37 | author_name: release robot
38 | author_email: robot@featureprobe.com
39 | cwd: './sdk-ios/client-sdk-ios/'
40 | push: ' https://${{ secrets.IOS_RELEASE_TOKEN }}@github.com/FeatureProbe/client-sdk-ios.git HEAD:main'
41 | - name: update ios submodule
42 | uses: EndBug/add-and-commit@v9.1.0
43 | with:
44 | message: 'update ios submodule'
45 | author_name: release robot
46 | author_email: robot@featureprobe.com
47 | push: 'origin main'
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/.github/workflows/rust.yml:
--------------------------------------------------------------------------------
1 | name: Rust
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v3
19 | - uses: raftario/setup-rust-action@v1
20 | with:
21 | rust-channel: nightly
22 | - name: Run build
23 | run: cargo +nightly build --verbose
24 | - name: Run tests
25 | run: cargo +nightly test --package feature_probe_mobile_sdk_core
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | .DS_Store
3 | .idea
4 | Podfile.lock
5 | Pods/
6 | *.xcworkspace/
7 | .vscode
8 | examples/demo-cmd/target/
9 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "sdk-ios/client-sdk-ios"]
2 | path = sdk-ios/client-sdk-ios
3 | url = https://github.com/FeatureProbe/client-sdk-ios.git
4 |
--------------------------------------------------------------------------------
/.rusty-hook.toml:
--------------------------------------------------------------------------------
1 | [hooks]
2 |
3 | [logging]
4 | verbose = true
5 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | members = ["rust-core", "rust-uniffi", "examples/demo-cmd"]
3 |
4 | [profile.release]
5 | lto = true
6 | strip = true # Automatically strip symbols from the binary.
7 | opt-level = "s" # Optimize for size.
8 | panic = "abort"
9 | codegen-units = 1
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 FeatureProbe
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | build_date = `date +%Y%m%d%H%M`
2 | commit = `git rev-parse HEAD`
3 | version = `git rev-parse --short HEAD`
4 |
5 | build:
6 | make build_android
7 | make build_ios
8 | clean:
9 | cargo clean
10 | build_android:
11 | rustup component add rust-src
12 | cargo install --version 0.21.0 uniffi_bindgen
13 | rustup target add armv7-linux-androideabi
14 | rustup target add aarch64-apple-darwin
15 | rustup target add i686-linux-android
16 | rustup target add x86_64-linux-android
17 | rustup target add aarch64-linux-android
18 | cd sdk-android && ./gradlew clean && ./gradlew build
19 | build_ios:
20 | rustup component add rust-src
21 | cargo install --version 0.21.0 uniffi_bindgen
22 | rustup target add aarch64-apple-ios
23 | rustup target add aarch64-apple-ios-sim
24 | rustup target add x86_64-apple-ios
25 | cd sdk-ios && ./build-xcframework.sh
26 | test:
27 | cargo test --verbose
28 |
29 |
30 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # FeatureProbe Client Side SDK for Mobile Apps
2 |
3 | [FeatureProbe](https://featureprobe.com/) is an open source feature management service. This SDK is used to control features in mobile programs.
4 |
5 | ## Basic Terms
6 |
7 | Reading the short [Introduction](https://docs.featureprobe.io/reference/sdk-introduction) will help to understand the code blow more easily. [中文](https://docs.featureprobe.io/zh-CN/reference/sdk-introduction)
8 |
9 | ## How to use this SDK
10 |
11 | See [Android](https://docs.featureprobe.io/how-to/Client-Side%20SDKs/android-sdk) [iOS](https://docs.featureprobe.io/how-to/Client-Side%20SDKs/ios-sdk) SDK Doc for detail. [安卓](https://docs.featureprobe.io/zh-CN/how-to/Client-Side%20SDKs/android-sdk) [苹果](https://docs.featureprobe.io/zh-CN/how-to/Client-Side%20SDKs/ios-sdk)
12 |
13 | ## Contributing
14 |
15 | We are working on continue evolving FeatureProbe core, making it flexible and easier to use.
16 | Development of FeatureProbe happens in the open on GitHub, and we are grateful to the
17 | community for contributing bugfixes and improvements.
18 |
19 | Please read [CONTRIBUTING](https://github.com/FeatureProbe/featureprobe/blob/master/CONTRIBUTING.md)
20 | for details on our code of conduct, and the process for taking part in improving FeatureProbe.
21 |
--------------------------------------------------------------------------------
/examples/.gitignore:
--------------------------------------------------------------------------------
1 | *.xcodeproj
2 | .DS_Store
3 |
4 |
--------------------------------------------------------------------------------
/examples/demo-android/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/examples/demo-android/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/examples/demo-android/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | }
5 |
6 | android {
7 | compileSdk 32
8 |
9 | defaultConfig {
10 | applicationId "com.featureprobe.demoandroid"
11 | minSdk 21
12 | targetSdk 32
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | compileOptions {
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | kotlinOptions {
30 | jvmTarget = '1.8'
31 | }
32 | buildFeatures {
33 | viewBinding true
34 | }
35 | }
36 |
37 | dependencies {
38 | implementation 'com.featureprobe:client-sdk-android:2.0.2@aar'
39 | implementation "net.java.dev.jna:jna:5.7.0@aar"
40 |
41 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
42 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
43 | implementation 'com.android.support:appcompat-v7:28.0.0'
44 | implementation 'com.android.support:design:28.0.0'
45 | implementation 'com.android.support.constraint:constraint-layout:2.0.4'
46 | implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0'
47 | implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0'
48 | testImplementation 'junit:junit:4.13.2'
49 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
50 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
51 | }
--------------------------------------------------------------------------------
/examples/demo-android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/examples/demo-android/app/src/androidTest/java/com/featureprobe/demoandroid/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.demoandroid
2 |
3 | import android.support.test.InstrumentationRegistry
4 | import android.support.test.runner.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.featureprobe.demoandroid", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
19 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/java/com/featureprobe/demoandroid/FirstFragment.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.demoandroid
2 |
3 | import android.os.Bundle
4 | import android.support.v4.app.Fragment
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import androidx.navigation.fragment.findNavController
9 | import com.featureprobe.demoandroid.databinding.FragmentFirstBinding
10 |
11 | /**
12 | * A simple [Fragment] subclass as the default destination in the navigation.
13 | */
14 | class FirstFragment : Fragment() {
15 |
16 | private var _binding: FragmentFirstBinding? = null
17 |
18 | // This property is only valid between onCreateView and
19 | // onDestroyView.
20 | private val binding get() = _binding!!
21 |
22 | override fun onCreateView(
23 | inflater: LayoutInflater, container: ViewGroup?,
24 | savedInstanceState: Bundle?
25 | ): View? {
26 |
27 | _binding = FragmentFirstBinding.inflate(inflater, container, false)
28 | return binding.root
29 |
30 | }
31 |
32 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
33 | super.onViewCreated(view, savedInstanceState)
34 |
35 | binding.buttonFirst.setOnClickListener {
36 | findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
37 | }
38 | }
39 |
40 | override fun onDestroyView() {
41 | super.onDestroyView()
42 | _binding = null
43 | }
44 | }
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/java/com/featureprobe/demoandroid/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.demoandroid
2 |
3 | import android.os.Bundle
4 | import android.support.design.widget.Snackbar
5 | import android.support.v7.app.AppCompatActivity
6 | import android.util.Log
7 | import androidx.navigation.findNavController
8 | import androidx.navigation.ui.AppBarConfiguration
9 | import androidx.navigation.ui.navigateUp
10 | import androidx.navigation.ui.setupActionBarWithNavController
11 | import android.view.Menu
12 | import android.view.MenuItem
13 | import com.featureprobe.demoandroid.databinding.ActivityMainBinding
14 | import com.featureprobe.mobile.*
15 | import kotlinx.coroutines.Dispatchers
16 | import kotlinx.coroutines.GlobalScope
17 | import kotlinx.coroutines.delay
18 | import kotlinx.coroutines.launch
19 |
20 |
21 | class MainActivity : AppCompatActivity() {
22 |
23 | private lateinit var appBarConfiguration: AppBarConfiguration
24 | private lateinit var binding: ActivityMainBinding
25 | private lateinit var featureprobe: FeatureProbe
26 |
27 | override fun onCreate(savedInstanceState: Bundle?) {
28 | super.onCreate(savedInstanceState)
29 |
30 | binding = ActivityMainBinding.inflate(layoutInflater)
31 | setContentView(binding.root)
32 |
33 | setSupportActionBar(binding.toolbar)
34 |
35 | val navController = findNavController(R.id.nav_host_fragment_content_main)
36 | appBarConfiguration = AppBarConfiguration(navController.graph)
37 | setupActionBarWithNavController(navController, appBarConfiguration)
38 |
39 | binding.fab.setOnClickListener { view ->
40 | Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
41 | .setAction("Action", null).show()
42 | }
43 |
44 | GlobalScope.launch(context = Dispatchers.IO) {
45 | val url = FpUrlBuilder("https://featureprobe.io/server").build()
46 | // val url = FpUrlBuilder("http://server_ip:4007").build() // for local docker
47 | val user = FpUser()
48 | user.with("city", "1")
49 | val config = FpConfig(url!!, "client-25614c7e03e9cb49c0e96357b797b1e47e7f2dff", 10u, 2u)
50 | featureprobe = FeatureProbe(config, user)
51 | while (true) {
52 | val toggleValue = featureprobe.boolDetail("campaign_allow_list", false)
53 | Log.d("demo", "toggle value is $toggleValue")
54 | featureprobe.track("eventWithoutValue")
55 | featureprobe.track("eventWithValue", 2.0)
56 | delay(3000)
57 | }
58 | // stop sync toggles and flush events
59 | // featureprobe.close();
60 | }
61 | }
62 |
63 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
64 | // Inflate the menu; this adds items to the action bar if it is present.
65 | menuInflater.inflate(R.menu.menu_main, menu)
66 | return true
67 | }
68 |
69 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
70 | // Handle action bar item clicks here. The action bar will
71 | // automatically handle clicks on the Home/Up button, so long
72 | // as you specify a parent activity in AndroidManifest.xml.
73 | return when (item.itemId) {
74 | R.id.action_settings -> true
75 | else -> super.onOptionsItemSelected(item)
76 | }
77 | }
78 |
79 | override fun onSupportNavigateUp(): Boolean {
80 | val navController = findNavController(R.id.nav_host_fragment_content_main)
81 | return navController.navigateUp(appBarConfiguration)
82 | || super.onSupportNavigateUp()
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/java/com/featureprobe/demoandroid/SecondFragment.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.demoandroid
2 |
3 | import android.os.Bundle
4 | import android.support.v4.app.Fragment
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import androidx.navigation.fragment.findNavController
9 | import com.featureprobe.demoandroid.databinding.FragmentSecondBinding
10 |
11 | /**
12 | * A simple [Fragment] subclass as the second destination in the navigation.
13 | */
14 | class SecondFragment : Fragment() {
15 |
16 | private var _binding: FragmentSecondBinding? = null
17 |
18 | // This property is only valid between onCreateView and
19 | // onDestroyView.
20 | private val binding get() = _binding!!
21 |
22 | override fun onCreateView(
23 | inflater: LayoutInflater, container: ViewGroup?,
24 | savedInstanceState: Bundle?
25 | ): View? {
26 |
27 | _binding = FragmentSecondBinding.inflate(inflater, container, false)
28 | return binding.root
29 |
30 | }
31 |
32 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
33 | super.onViewCreated(view, savedInstanceState)
34 |
35 | binding.buttonSecond.setOnClickListener {
36 | findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
37 | }
38 | }
39 |
40 | override fun onDestroyView() {
41 | super.onDestroyView()
42 | _binding = null
43 | }
44 | }
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
20 |
21 |
22 |
23 |
24 |
25 |
33 |
34 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
19 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/layout/fragment_first.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
18 |
19 |
28 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/layout/fragment_second.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
27 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/navigation/nav_graph.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
17 |
18 |
23 |
24 |
27 |
28 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values-land/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values-w1240dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 200dp
3 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values-w600dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 48dp
3 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DemoAndroid
3 | Settings
4 |
5 | First Fragment
6 | Second Fragment
7 | Next
8 | Previous
9 |
10 | Hello first fragment
11 | Hello second fragment. Arg: %1$s
12 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/main/res/xml/network_security.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/examples/demo-android/app/src/test/java/com/featureprobe/demoandroid/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.demoandroid
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/examples/demo-android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id 'com.android.application' version '7.2.2' apply false
4 | id 'com.android.library' version '7.2.2' apply false
5 | id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
6 | }
7 |
8 | task clean(type: Delete) {
9 | delete rootProject.buildDir
10 | }
--------------------------------------------------------------------------------
/examples/demo-android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # Kotlin code style for this project: "official" or "obsolete":
15 | kotlin.code.style=official
16 | # Enables namespacing of each library's R class so that its R class includes only the
17 | # resources declared in the library itself and none from the library's dependencies,
18 | # thereby reducing the size of the R class for that library
19 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/examples/demo-android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/examples/demo-android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/examples/demo-android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Aug 26 11:07:39 HKT 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/examples/demo-android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/examples/demo-android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/examples/demo-android/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "DemoAndroid"
16 | include ':app'
17 |
--------------------------------------------------------------------------------
/examples/demo-cmd/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "demo-cmd"
3 | version = "0.1.0"
4 | edition = "2021"
5 |
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7 |
8 | [dependencies]
9 | tracing = "0.1"
10 | tracing-subscriber = { version = "0.3", features = ["env-filter"] }
11 | tokio = { version = "1", features = ["full"] }
12 | feature_probe_mobile_sdk_core = { path = "../../rust-core" }
13 |
--------------------------------------------------------------------------------
/examples/demo-cmd/src/main.rs:
--------------------------------------------------------------------------------
1 | use std::time::Duration;
2 |
3 | use feature_probe_mobile_sdk_core::{FPConfig, FPUser, FeatureProbe, Url};
4 | use tracing::info;
5 |
6 | #[tokio::main]
7 | async fn main() {
8 | tracing_subscriber::fmt::init();
9 |
10 | let toggles_url = Url::parse("https://featureprobe.io/server/api/client-sdk/toggles").unwrap();
11 | let events_url = Url::parse("https://featureprobe.io/server/api/events").unwrap();
12 | let realtime_url = Url::parse("https://featureprobe.io/server/realtime").unwrap();
13 | let client_sdk_key = "client-75d9182a7724b03d531178142b9031b831e464fe".to_owned();
14 | let refresh_interval = Duration::from_secs(100);
15 | let start_wait = Some(Duration::from_secs(3));
16 | let config = FPConfig {
17 | toggles_url,
18 | events_url,
19 | realtime_url,
20 | client_sdk_key,
21 | refresh_interval,
22 | start_wait,
23 | };
24 |
25 | let user = FPUser::new("uniq_key");
26 |
27 | let fp = FeatureProbe::new(config, user);
28 |
29 | loop {
30 | let d = fp.bool_detail("campaign_allow_list", false);
31 | info!("detail {:?}", d);
32 |
33 | tokio::time::sleep(Duration::from_secs(3)).await;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Demo/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import FeatureProbe
3 |
4 | @UIApplicationMain
5 | class AppDelegate: UIResponder, UIApplicationDelegate {
6 |
7 | var window: UIWindow?
8 |
9 | func testToggle() {
10 | let urlStr = "https://featureprobe.io/server"
11 | // let urlStr = "http://server_ip:4007" // for local docker
12 | let user = FpUser()
13 | user.with(key: "city", value: "1")
14 | let url = FpUrlBuilder(remoteUrl: urlStr).build()
15 | let config = FpConfig(
16 | remoteUrl: url!,
17 | // this key just for demo, you should copy from project list
18 | clientSdkKey: "client-25614c7e03e9cb49c0e96357b797b1e47e7f2dff",
19 | refreshInterval: 10,
20 | startWait: 2
21 | )
22 | let fp = FeatureProbe(config: config, user: user)
23 | let toggleValue = fp.boolDetail(key: "campaign_allow_list", defaultValue: false)
24 | print("toogle value is \( toggleValue)")
25 | fp.track(event: "event_without_value")
26 | fp.track(event: "event_with_value", value: 3.0)
27 | fp.close() // stop sync toggles and flush events
28 | }
29 |
30 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
31 | // Override point for customization after application launch.
32 | self.testToggle()
33 | return true
34 | }
35 |
36 | func applicationWillResignActive(_ application: UIApplication) {
37 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
38 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
39 | }
40 |
41 | func applicationDidEnterBackground(_ application: UIApplication) {
42 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
43 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
44 | }
45 |
46 | func applicationWillEnterForeground(_ application: UIApplication) {
47 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
48 | }
49 |
50 | func applicationDidBecomeActive(_ application: UIApplication) {
51 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
52 | }
53 |
54 | func applicationWillTerminate(_ application: UIApplication) {
55 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
56 | }
57 |
58 |
59 | }
60 |
61 |
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Demo/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "20x20",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "20x20",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "29x29",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "29x29",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "40x40",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "40x40",
31 | "scale" : "3x"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "size" : "60x60",
36 | "scale" : "2x"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "size" : "60x60",
41 | "scale" : "3x"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "size" : "20x20",
46 | "scale" : "1x"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "size" : "20x20",
51 | "scale" : "2x"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "size" : "29x29",
56 | "scale" : "1x"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "size" : "29x29",
61 | "scale" : "2x"
62 | },
63 | {
64 | "idiom" : "ipad",
65 | "size" : "40x40",
66 | "scale" : "1x"
67 | },
68 | {
69 | "idiom" : "ipad",
70 | "size" : "40x40",
71 | "scale" : "2x"
72 | },
73 | {
74 | "idiom" : "ipad",
75 | "size" : "76x76",
76 | "scale" : "1x"
77 | },
78 | {
79 | "idiom" : "ipad",
80 | "size" : "76x76",
81 | "scale" : "2x"
82 | },
83 | {
84 | "idiom" : "ipad",
85 | "size" : "83.5x83.5",
86 | "scale" : "2x"
87 | }
88 | ],
89 | "info" : {
90 | "version" : 1,
91 | "author" : "xcode"
92 | }
93 | }
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Demo/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Demo/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Demo/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleVersion
20 | 1
21 | LSRequiresIPhoneOS
22 |
23 | UILaunchStoryboardName
24 | LaunchScreen
25 | UIMainStoryboardFile
26 | Main
27 | UIRequiredDeviceCapabilities
28 |
29 | armv7
30 |
31 | UISupportedInterfaceOrientations
32 |
33 | UIInterfaceOrientationPortrait
34 | UIInterfaceOrientationLandscapeLeft
35 | UIInterfaceOrientationLandscapeRight
36 |
37 | UISupportedInterfaceOrientations~ipad
38 |
39 | UIInterfaceOrientationPortrait
40 | UIInterfaceOrientationPortraitUpsideDown
41 | UIInterfaceOrientationLandscapeLeft
42 | UIInterfaceOrientationLandscapeRight
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Demo/ViewController.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | class ViewController: UIViewController {
4 |
5 | override func viewDidLoad() {
6 | super.viewDidLoad()
7 | // Do any additional setup after loading the view, typically from a nib.
8 | }
9 |
10 | override func didReceiveMemoryWarning() {
11 | super.didReceiveMemoryWarning()
12 | // Dispose of any resources that can be recreated.
13 | }
14 |
15 |
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/examples/demo-cocoapods/Podfile:
--------------------------------------------------------------------------------
1 | # Uncomment the next line to define a global platform for your project
2 | platform :ios, '10.0'
3 |
4 | target 'Demo' do
5 | # Comment the next line if you don't want to use dynamic frameworks
6 | use_frameworks!
7 |
8 | # Pods for Demo
9 | pod 'FeatureProbe', '2.0.2'
10 |
11 | end
12 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import
9 |
10 | @interface AppDelegate : UIResponder
11 |
12 |
13 | @end
14 |
15 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import "AppDelegate.h"
9 | #import "FeatureProbe-Swift.h"
10 |
11 | @interface AppDelegate ()
12 |
13 | @end
14 |
15 | @implementation AppDelegate
16 |
17 |
18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
19 | NSString *urlStr = @"https://featureprobe.io/server";
20 | // NSString *urlStr = @"http://server_ip:4007"; // for local docker
21 |
22 | FpUrl *url = [[[FpUrlBuilder alloc] initWithRemoteUrl: urlStr] build];
23 | FpUser *user = [[FpUser alloc] init];
24 | [user withKey:@"city" value:@"1"];
25 |
26 | // this key just for demo, you should copy from project list
27 | NSString *key = @"client-25614c7e03e9cb49c0e96357b797b1e47e7f2dff";
28 | FpConfig *config = [[FpConfig alloc] initWithRemoteUrl: url
29 | clientSdkKey: key
30 | refreshInterval: 10
31 | startWait: 2];
32 |
33 | FeatureProbe *fp = [[FeatureProbe alloc] initWithConfig:config user:user];
34 | FpBoolDetail *detail = [fp boolDetailWithKey:@"campaign_allow_list" defaultValue: false];
35 | NSLog(@"value is %d, reason is %@", detail.value, detail.reason);
36 |
37 | [fp trackWithEvent:@"EventWithoutValue"];
38 | [fp trackWithEvent:@"EventWithValue" value:2.0];
39 | [fp close]; // stop sync toggles and flush events
40 |
41 | return YES;
42 | }
43 |
44 |
45 | #pragma mark - UISceneSession lifecycle
46 |
47 |
48 | - (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
49 | // Called when a new scene session is being created.
50 | // Use this method to select a configuration to create the new scene with.
51 | return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
52 | }
53 |
54 |
55 | - (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet *)sceneSessions {
56 | // Called when the user discards a scene session.
57 | // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
58 | // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
59 | }
60 |
61 |
62 | @end
63 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/Assets.xcassets/AccentColor.colorset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "colors" : [
3 | {
4 | "idiom" : "universal"
5 | }
6 | ],
7 | "info" : {
8 | "author" : "xcode",
9 | "version" : 1
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "scale" : "1x",
46 | "size" : "20x20"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "scale" : "2x",
51 | "size" : "20x20"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "scale" : "1x",
56 | "size" : "29x29"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "scale" : "2x",
61 | "size" : "29x29"
62 | },
63 | {
64 | "idiom" : "ipad",
65 | "scale" : "1x",
66 | "size" : "40x40"
67 | },
68 | {
69 | "idiom" : "ipad",
70 | "scale" : "2x",
71 | "size" : "40x40"
72 | },
73 | {
74 | "idiom" : "ipad",
75 | "scale" : "2x",
76 | "size" : "76x76"
77 | },
78 | {
79 | "idiom" : "ipad",
80 | "scale" : "2x",
81 | "size" : "83.5x83.5"
82 | },
83 | {
84 | "idiom" : "ios-marketing",
85 | "scale" : "1x",
86 | "size" : "1024x1024"
87 | }
88 | ],
89 | "info" : {
90 | "author" : "xcode",
91 | "version" : 1
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | UIApplicationSceneManifest
6 |
7 | UIApplicationSupportsMultipleScenes
8 |
9 | UISceneConfigurations
10 |
11 | UIWindowSceneSessionRoleApplication
12 |
13 |
14 | UISceneConfigurationName
15 | Default Configuration
16 | UISceneDelegateClassName
17 | SceneDelegate
18 | UISceneStoryboardFile
19 | Main
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/SceneDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // SceneDelegate.h
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import
9 |
10 | @interface SceneDelegate : UIResponder
11 |
12 | @property (strong, nonatomic) UIWindow * window;
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/SceneDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // SceneDelegate.m
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import "SceneDelegate.h"
9 |
10 | @interface SceneDelegate ()
11 |
12 | @end
13 |
14 | @implementation SceneDelegate
15 |
16 |
17 | - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
18 | // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
19 | // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
20 | // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
21 | }
22 |
23 |
24 | - (void)sceneDidDisconnect:(UIScene *)scene {
25 | // Called as the scene is being released by the system.
26 | // This occurs shortly after the scene enters the background, or when its session is discarded.
27 | // Release any resources associated with this scene that can be re-created the next time the scene connects.
28 | // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
29 | }
30 |
31 |
32 | - (void)sceneDidBecomeActive:(UIScene *)scene {
33 | // Called when the scene has moved from an inactive state to an active state.
34 | // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
35 | }
36 |
37 |
38 | - (void)sceneWillResignActive:(UIScene *)scene {
39 | // Called when the scene will move from an active state to an inactive state.
40 | // This may occur due to temporary interruptions (ex. an incoming phone call).
41 | }
42 |
43 |
44 | - (void)sceneWillEnterForeground:(UIScene *)scene {
45 | // Called as the scene transitions from the background to the foreground.
46 | // Use this method to undo the changes made on entering the background.
47 | }
48 |
49 |
50 | - (void)sceneDidEnterBackground:(UIScene *)scene {
51 | // Called as the scene transitions from the foreground to the background.
52 | // Use this method to save data, release shared resources, and store enough scene-specific state information
53 | // to restore the scene back to its current state.
54 | }
55 |
56 |
57 | @end
58 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import
9 |
10 | @interface ViewController : UIViewController
11 |
12 |
13 | @end
14 |
15 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/ViewController.m:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.m
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import "ViewController.h"
9 |
10 | @interface ViewController ()
11 |
12 | @end
13 |
14 | @implementation ViewController
15 |
16 | - (void)viewDidLoad {
17 | [super viewDidLoad];
18 | // Do any additional setup after loading the view.
19 | }
20 |
21 |
22 | @end
23 |
--------------------------------------------------------------------------------
/examples/demo-objc/Demo/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // Demo
4 | //
5 | // Created by sebo on 2022/5/13.
6 | //
7 |
8 | #import
9 | #import "AppDelegate.h"
10 |
11 | int main(int argc, char * argv[]) {
12 | NSString * appDelegateClassName;
13 | @autoreleasepool {
14 | // Setup code that might create autoreleased objects goes here.
15 | appDelegateClassName = NSStringFromClass([AppDelegate class]);
16 | }
17 | return UIApplicationMain(argc, argv, nil, appDelegateClassName);
18 | }
19 |
--------------------------------------------------------------------------------
/examples/demo-objc/Podfile:
--------------------------------------------------------------------------------
1 | # Uncomment the next line to define a global platform for your project
2 | platform :ios, '10.0'
3 |
4 | target 'Demo' do
5 | # Comment the next line if you don't want to use dynamic frameworks
6 | use_frameworks!
7 |
8 | # Pods for Demo
9 | pod 'FeatureProbe', "2.0.2"
10 | end
11 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /.build
3 | /Packages
4 | xcuserdata/
5 | DerivedData/
6 | .swiftpm/config/registries.json
7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
8 | .netrc
9 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/Demo/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 | import FeatureProbe
3 |
4 |
5 | @UIApplicationMain
6 | class AppDelegate: UIResponder, UIApplicationDelegate {
7 |
8 | var window: UIWindow?
9 | var fp: FeatureProbe?
10 |
11 | @objc
12 | func testToggle() {
13 | let urlStr = "https://featureprobe.io/server";
14 | // let urlStr = "http://server_ip:4007"; // for local docker
15 | let url = FpUrlBuilder(remoteUrl: urlStr).build()
16 | let user = FpUser()
17 | user.with(key: "city", value: "1")
18 | let config = FpConfig(
19 | remoteUrl: url!,
20 | clientSdkKey: "client-75d9182a7724b03d531178142b9031b831e464fe",
21 | refreshInterval: 200,
22 | startWait: 2
23 | )
24 |
25 | self.fp = FeatureProbe(config: config, user: user)
26 |
27 | Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.boolDetail), userInfo: nil, repeats: true)
28 |
29 | //fp.close() // stop sync toggles and flush events
30 | }
31 |
32 | @objc
33 | func boolDetail() {
34 | let toggleValue = self.fp?.boolDetail(key: "campaign_allow_list", defaultValue: false)
35 | print("toogle value is \( String(describing: toggleValue) )")
36 | self.fp?.track(event: "NoValueEvent")
37 | self.fp?.track(event: "EventWithValue", value: 2.0)
38 | }
39 |
40 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
41 | // Override point for customization after application launch.
42 |
43 | testToggle()
44 | return true
45 | }
46 |
47 | func applicationWillResignActive(_ application: UIApplication) {
48 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
49 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
50 | }
51 |
52 | func applicationDidEnterBackground(_ application: UIApplication) {
53 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
54 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
55 | }
56 |
57 | func applicationWillEnterForeground(_ application: UIApplication) {
58 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
59 | }
60 |
61 | func applicationDidBecomeActive(_ application: UIApplication) {
62 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
63 | }
64 |
65 | func applicationWillTerminate(_ application: UIApplication) {
66 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
67 | }
68 |
69 |
70 | }
71 |
72 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/Demo/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "scale" : "1x",
46 | "size" : "20x20"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "scale" : "2x",
51 | "size" : "20x20"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "scale" : "1x",
56 | "size" : "29x29"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "scale" : "2x",
61 | "size" : "29x29"
62 | },
63 | {
64 | "idiom" : "ipad",
65 | "scale" : "1x",
66 | "size" : "40x40"
67 | },
68 | {
69 | "idiom" : "ipad",
70 | "scale" : "2x",
71 | "size" : "40x40"
72 | },
73 | {
74 | "idiom" : "ipad",
75 | "scale" : "1x",
76 | "size" : "76x76"
77 | },
78 | {
79 | "idiom" : "ipad",
80 | "scale" : "2x",
81 | "size" : "76x76"
82 | },
83 | {
84 | "idiom" : "ipad",
85 | "scale" : "2x",
86 | "size" : "83.5x83.5"
87 | },
88 | {
89 | "idiom" : "ios-marketing",
90 | "scale" : "1x",
91 | "size" : "1024x1024"
92 | }
93 | ],
94 | "info" : {
95 | "author" : "xcode",
96 | "version" : 1
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/Demo/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/Demo/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/Demo/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleVersion
20 | 1
21 | LSRequiresIPhoneOS
22 |
23 | UILaunchStoryboardName
24 | LaunchScreen
25 | UIMainStoryboardFile
26 | Main
27 | UIRequiredDeviceCapabilities
28 |
29 | armv7
30 |
31 | UISupportedInterfaceOrientations
32 |
33 | UIInterfaceOrientationPortrait
34 | UIInterfaceOrientationLandscapeLeft
35 | UIInterfaceOrientationLandscapeRight
36 |
37 | UISupportedInterfaceOrientations~ipad
38 |
39 | UIInterfaceOrientationPortrait
40 | UIInterfaceOrientationPortraitUpsideDown
41 | UIInterfaceOrientationLandscapeLeft
42 | UIInterfaceOrientationLandscapeRight
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/examples/demo-swiftpm/Demo/ViewController.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | class ViewController: UIViewController {
4 |
5 | override func viewDidLoad() {
6 | super.viewDidLoad()
7 | // Do any additional setup after loading the view, typically from a nib.
8 | }
9 |
10 | override func didReceiveMemoryWarning() {
11 | super.didReceiveMemoryWarning()
12 | // Dispose of any resources that can be recreated.
13 | }
14 |
15 |
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/rust-core/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | edition = "2021"
3 | name = "feature_probe_mobile_sdk_core"
4 | version = "1.0.2"
5 | build = "build.rs"
6 |
7 | [lib]
8 | name = "feature_probe_mobile_sdk_core"
9 | path = "src/lib.rs"
10 |
11 | [[bench]]
12 | harness = false
13 | name = "bench"
14 |
15 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
16 |
17 | [dependencies]
18 | anyhow = "1.0"
19 | base64 = "0.13"
20 | byteorder = "1"
21 | dashmap = "5.1"
22 | headers = "0.3"
23 | http = "0.2"
24 | lazy_static = "1.4"
25 | parking_lot = "0.12"
26 | rand = "0.8"
27 | regex = "1.5.6"
28 | reqwest = { version = "0.11", default-features = false, features = [
29 | "rustls-tls",
30 | ] }
31 | semver = "1.0"
32 | serde = { version = "1.0", features = ["derive"] }
33 | serde_json = "1.0"
34 | sha1 = "0.10"
35 | thiserror = "1.0"
36 | tokio = { version = "1", features = ["full"] }
37 | tracing = "0.1"
38 | url = "2"
39 | socketio-rs = { version = "0.1.7", default-features = false, features = ["client"]}
40 | futures-util = { version = "0.3", default-features = false, features = [
41 | "sink",
42 | ] }
43 |
44 | feature-probe-event = { version = "1.2.0", features = [
45 | "use_tokio",
46 | ], default-features = false }
47 |
48 | [dev-dependencies]
49 | approx = "0.5"
50 | axum = { version = "0.5", features = ["headers"] }
51 | axum-extra = { version = "0.2", features = ["typed-routing"] }
52 | clap = { version = "3.1.10", features = ["derive"] }
53 | criterion = "0.3"
54 | rusty-hook = "^0.11.2"
55 | tracing-subscriber = "0.3"
56 |
57 | feature-probe-server = "2.0.1"
58 |
--------------------------------------------------------------------------------
/rust-core/benches/bench.rs:
--------------------------------------------------------------------------------
1 | use criterion::{black_box, criterion_group, criterion_main, Criterion};
2 | use feature_probe_mobile_sdk_core::{FeatureProbe, Repository};
3 | use serde_json::json;
4 | use std::{fs, path::PathBuf};
5 |
6 | fn bench_bool_toggle(fp: &FeatureProbe) {
7 | let _d = fp.bool_detail("bool_toogle", false);
8 | }
9 |
10 | fn bench_json_toggle(fp: &FeatureProbe) {
11 | let _d = fp.json_detail("multi_condition_toggle", json!(""));
12 | }
13 |
14 | fn load_json() -> Repository {
15 | let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
16 | path.push("resources/fixtures/toggles.json");
17 | let json_str = fs::read_to_string(path).unwrap();
18 | serde_json::from_str(&json_str).unwrap()
19 | }
20 |
21 | //TODO: simulate repo read lock vs write lock with specific ratio
22 | fn criterion_benchmark(c: &mut Criterion) {
23 | let repo = load_json();
24 | let fp = FeatureProbe::new_with(repo);
25 |
26 | c.bench_function("bench_bool_toggle", |b| {
27 | b.iter(|| bench_bool_toggle(black_box(&fp)))
28 | });
29 |
30 | c.bench_function("bench_json_toggle", |b| {
31 | b.iter(|| bench_json_toggle(black_box(&fp)))
32 | });
33 | }
34 |
35 | criterion_group!(benches, criterion_benchmark);
36 |
37 | criterion_main!(benches);
38 |
--------------------------------------------------------------------------------
/rust-core/build.rs:
--------------------------------------------------------------------------------
1 | // build.rs
2 |
3 | use std::env;
4 | use std::fs::File;
5 | use std::io::Write;
6 | use std::path::Path;
7 |
8 | fn main() {
9 | let out_dir = env::var("OUT_DIR").unwrap();
10 | let dest_path = Path::new(&out_dir).join("target_os.rs");
11 | let mut f = File::create(dest_path).unwrap();
12 | let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_else(|_| "uniffi".to_owned());
13 |
14 | let s = format!(
15 | "pub fn target_os() -> String {{
16 | \"{}\".to_owned()
17 | }}",
18 | target_os
19 | );
20 |
21 | f.write_all(&s.into_bytes()).unwrap();
22 | }
23 |
--------------------------------------------------------------------------------
/rust-core/resources/fixtures/repo.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": 1,
3 | "segments": {
4 | "some_segment1-fjoaefjaam": {
5 | "key": "some_segment1",
6 | "uniqueId": "some_segment1-fjoaefjaam",
7 | "version": 2,
8 | "rules": [
9 | {
10 | "conditions": [
11 | {
12 | "type": "string",
13 | "subject": "city",
14 | "predicate": "is one of",
15 | "objects": [
16 | "4"
17 | ]
18 | }
19 | ]
20 | }
21 | ]
22 | }
23 | },
24 | "toggles": {
25 | "bool_toggle": {
26 | "key": "bool_toggle",
27 | "enabled": true,
28 | "forClient": true,
29 | "version": 1,
30 | "disabledServe": {
31 | "select": 1
32 | },
33 | "defaultServe": {
34 | "select": 0
35 | },
36 | "trackAccessEvents": false,
37 | "rules": [
38 | {
39 | "serve": {
40 | "select": 0
41 | },
42 | "conditions": [
43 | {
44 | "type": "string",
45 | "subject": "city",
46 | "predicate": "is one of",
47 | "objects": [
48 | "1",
49 | "2",
50 | "3"
51 | ]
52 | }
53 | ]
54 | },
55 | {
56 | "serve": {
57 | "select": 1
58 | },
59 | "conditions": [
60 | {
61 | "type": "segment",
62 | "subject": "user",
63 | "predicate": "in",
64 | "objects": [
65 | "some_segment1-fjoaefjaam"
66 | ]
67 | }
68 | ]
69 | }
70 | ],
71 | "variations": [
72 | true,
73 | false
74 | ]
75 | },
76 | "number_toggle": {
77 | "key": "number_toggle",
78 | "forClient": true,
79 | "enabled": true,
80 | "version": 1,
81 | "disabledServe": {
82 | "select": 1
83 | },
84 | "defaultServe": {
85 | "select": 0
86 | },
87 | "trackAccessEvents": false,
88 | "rules": [
89 | {
90 | "serve": {
91 | "select": 0
92 | },
93 | "conditions": [
94 | {
95 | "type": "string",
96 | "subject": "city",
97 | "predicate": "is one of",
98 | "objects": [
99 | "1",
100 | "2",
101 | "3"
102 | ]
103 | }
104 | ]
105 | },
106 | {
107 | "serve": {
108 | "select": 1
109 | },
110 | "conditions": [
111 | {
112 | "type": "segment",
113 | "subject": "user",
114 | "predicate": "in",
115 | "objects": [
116 | "some_segment1-fjoaefjaam"
117 | ]
118 | }
119 | ]
120 | }
121 | ],
122 | "variations": [
123 | 1,
124 | 2
125 | ]
126 | },
127 | "string_toggle": {
128 | "key": "string_toggle",
129 | "forClient": true,
130 | "enabled": true,
131 | "version": 1,
132 | "disabledServe": {
133 | "select": 1
134 | },
135 | "defaultServe": {
136 | "select": 0
137 | },
138 | "trackAccessEvents": false,
139 | "rules": [
140 | {
141 | "serve": {
142 | "select": 0
143 | },
144 | "conditions": [
145 | {
146 | "type": "string",
147 | "subject": "city",
148 | "predicate": "is one of",
149 | "objects": [
150 | "1",
151 | "2",
152 | "3"
153 | ]
154 | }
155 | ]
156 | },
157 | {
158 | "serve": {
159 | "select": 1
160 | },
161 | "conditions": [
162 | {
163 | "type": "segment",
164 | "subject": "user",
165 | "predicate": "in",
166 | "objects": [
167 | "some_segment1-fjoaefjaam"
168 | ]
169 | }
170 | ]
171 | }
172 | ],
173 | "variations": [
174 | "1",
175 | "2"
176 | ]
177 | },
178 | "json_toggle": {
179 | "key": "json_toggle",
180 | "enabled": true,
181 | "forClient": true,
182 | "version": 1,
183 | "disabledServe": {
184 | "select": 1
185 | },
186 | "trackAccessEvents": false,
187 | "defaultServe": {
188 | "split": {
189 | "distribution": [
190 | [
191 | [
192 | 0,
193 | 3333
194 | ]
195 | ],
196 | [
197 | [
198 | 3333,
199 | 6666
200 | ]
201 | ],
202 | [
203 | [
204 | 6666,
205 | 10000
206 | ]
207 | ]
208 | ],
209 | "salt": "some_salt"
210 | }
211 | },
212 | "rules": [
213 | {
214 | "serve": {
215 | "select": 0
216 | },
217 | "conditions": [
218 | {
219 | "type": "string",
220 | "subject": "city",
221 | "predicate": "is one of",
222 | "objects": [
223 | "1",
224 | "2",
225 | "3"
226 | ]
227 | }
228 | ]
229 | },
230 | {
231 | "serve": {
232 | "select": 1
233 | },
234 | "conditions": [
235 | {
236 | "type": "segment",
237 | "subject": "user",
238 | "predicate": "in",
239 | "objects": [
240 | "some_segment1-fjoaefjaam"
241 | ]
242 | }
243 | ]
244 | }
245 | ],
246 | "variations": [
247 | {
248 | "variation_0": "c2",
249 | "v": "v1"
250 | },
251 | {
252 | "variation_1": "v2"
253 | },
254 | {
255 | "variation_2": "v3"
256 | }
257 | ]
258 | },
259 | "multi_condition_toggle": {
260 | "key": "multi_condition_toggle",
261 | "enabled": true,
262 | "forClient": true,
263 | "version": 1,
264 | "disabledServe": {
265 | "select": 1
266 | },
267 | "defaultServe": {
268 | "select": 1
269 | },
270 | "trackAccessEvents": false,
271 | "rules": [
272 | {
273 | "serve": {
274 | "select": 0
275 | },
276 | "conditions": [
277 | {
278 | "type": "string",
279 | "subject": "city",
280 | "predicate": "is one of",
281 | "objects": [
282 | "1",
283 | "2",
284 | "3"
285 | ]
286 | },
287 | {
288 | "type": "string",
289 | "subject": "os",
290 | "predicate": "is one of",
291 | "objects": [
292 | "mac",
293 | "linux"
294 | ]
295 | }
296 | ]
297 | }
298 | ],
299 | "variations": [
300 | {
301 | "variation_0": ""
302 | },
303 | {
304 | "disabled_key": "disabled_value"
305 | }
306 | ]
307 | },
308 | "disabled_toggle": {
309 | "key": "disabled_toggle",
310 | "enabled": false,
311 | "forClient": true,
312 | "version": 1,
313 | "disabledServe": {
314 | "select": 1
315 | },
316 | "defaultServe": {
317 | "select": 0
318 | },
319 | "trackAccessEvents": false,
320 | "rules": [],
321 | "variations": [
322 | {},
323 | {
324 | "disabled_key": "disabled_value"
325 | }
326 | ]
327 | },
328 | "server_toggle": {
329 | "key": "server_toggle",
330 | "enabled": false,
331 | "forClient": false,
332 | "version": 1,
333 | "disabledServe": {
334 | "select": 1
335 | },
336 | "defaultServe": {
337 | "select": 0
338 | },
339 | "trackAccessEvents": false,
340 | "rules": [],
341 | "variations": [
342 | {},
343 | {
344 | "disabled_key": "disabled_value"
345 | }
346 | ]
347 | }
348 | }
349 | }
350 |
--------------------------------------------------------------------------------
/rust-core/resources/fixtures/toggles.json:
--------------------------------------------------------------------------------
1 | {
2 | "disabled_toggle": {
3 | "trackAccessEvents": false,
4 | "value": {
5 | "disabled_key": "disabled_value"
6 | },
7 | "ruleIndex": null,
8 | "version": 1,
9 | "reason": "disabled"
10 | },
11 | "number_toggle": {
12 | "trackAccessEvents": false,
13 | "value": 1,
14 | "ruleIndex": 0,
15 | "version": 1,
16 | "reason": "rule 0"
17 | },
18 | "bool_toggle": {
19 | "trackAccessEvents": false,
20 | "value": true,
21 | "ruleIndex": 0,
22 | "version": 1,
23 | "reason": "rule 0"
24 | },
25 | "multi_condition_toggle": {
26 | "trackAccessEvents": false,
27 | "value": {
28 | "disabled_key": "disabled_value"
29 | },
30 | "ruleIndex": null,
31 | "version": 1,
32 | "reason": "default."
33 | },
34 | "json_toggle": {
35 | "trackAccessEvents": false,
36 | "value": {
37 | "v": "v1",
38 | "variation_0": "c2"
39 | },
40 | "ruleIndex": 0,
41 | "version": 1,
42 | "reason": "rule 0"
43 | },
44 | "string_toggle": {
45 | "trackAccessEvents": false,
46 | "value": "1",
47 | "ruleIndex": 0,
48 | "version": 1,
49 | "reason": "rule 0"
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/rust-core/resources/jna.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/rust-core/resources/jna.jar
--------------------------------------------------------------------------------
/rust-core/src/lib.rs:
--------------------------------------------------------------------------------
1 | mod feature_probe;
2 | mod sync;
3 | mod user;
4 |
5 | pub use crate::user::FPUser;
6 | pub use feature_probe::{FPConfig, FeatureProbe};
7 | use lazy_static::lazy_static;
8 | pub use url::Url;
9 |
10 | use headers::{Error, Header, HeaderName, HeaderValue};
11 | use http::header::AUTHORIZATION;
12 | use serde::{Deserialize, Serialize};
13 | use serde_json::Value;
14 | use std::{collections::HashMap, env};
15 | use thiserror::Error;
16 |
17 | include!(concat!(env!("OUT_DIR"), "/target_os.rs"));
18 |
19 | pub type Repository = HashMap>;
20 |
21 | const VERSION: &str = env!("CARGO_PKG_VERSION");
22 |
23 | lazy_static! {
24 | pub static ref USER_AGENT: String = user_agent();
25 | }
26 |
27 | #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, Eq)]
28 | #[serde(rename_all = "camelCase")]
29 | pub struct FPDetail {
30 | pub value: T,
31 | pub rule_index: Option,
32 | pub variation_index: Option,
33 | pub version: Option,
34 | pub reason: String,
35 | pub track_access_events: bool,
36 | pub debug_until_time: Option,
37 | }
38 |
39 | #[non_exhaustive]
40 | #[derive(Debug, Error)]
41 | pub enum FPError {
42 | #[error("invalid json: {0}")]
43 | JsonError(String),
44 | #[error("invalid http: {0}")]
45 | HttpError(String),
46 | #[error("invalid url: {0}")]
47 | UrlError(String),
48 | }
49 |
50 | #[derive(Debug, Deserialize)]
51 | pub struct SdkAuthorization(pub String);
52 |
53 | impl SdkAuthorization {
54 | pub fn encode(&self) -> HeaderValue {
55 | HeaderValue::from_str(&self.0).expect("valid header value")
56 | }
57 | }
58 |
59 | impl Header for SdkAuthorization {
60 | fn name() -> &'static HeaderName {
61 | &AUTHORIZATION
62 | }
63 |
64 | fn decode<'i, I>(values: &mut I) -> Result
65 | where
66 | Self: Sized,
67 | I: Iterator- ,
68 | {
69 | match values.next() {
70 | Some(v) => match v.to_str() {
71 | Ok(s) => Ok(SdkAuthorization(s.to_owned())),
72 | Err(_) => Err(Error::invalid()),
73 | },
74 | None => Err(Error::invalid()),
75 | }
76 | }
77 |
78 | fn encode>(&self, values: &mut E) {
79 | if let Ok(value) = HeaderValue::from_str(&self.0) {
80 | values.extend(std::iter::once(value))
81 | }
82 | }
83 | }
84 |
85 | fn user_agent() -> String {
86 | let mut target_os = target_os();
87 |
88 | if target_os.is_empty() {
89 | target_os = "uniffi".to_owned();
90 | }
91 |
92 | if &target_os == "ios" {
93 | target_os = "iOS".to_owned();
94 | } else {
95 | target_os = target_os[0..1].to_uppercase() + &target_os[1..];
96 | }
97 | format!("{}/{}", target_os, VERSION)
98 | }
99 |
--------------------------------------------------------------------------------
/rust-core/src/sync.rs:
--------------------------------------------------------------------------------
1 | use crate::{FPDetail, FPError, Repository};
2 | use headers::HeaderValue;
3 | use http::StatusCode;
4 | use parking_lot::RwLock;
5 | use reqwest::{header::AUTHORIZATION, header::USER_AGENT, Client, Method};
6 | use serde_json::Value;
7 | use std::{
8 | collections::HashMap,
9 | sync::{mpsc::sync_channel, Arc},
10 | time::{Duration, Instant},
11 | };
12 | use tracing::{debug, error, trace};
13 | use url::Url;
14 |
15 | #[derive(Debug, Clone)]
16 | pub struct Synchronizer {
17 | inner: Arc,
18 | }
19 |
20 | #[derive(Debug)]
21 | pub enum SyncType {
22 | Realtime,
23 | Polling,
24 | }
25 |
26 | #[derive(Debug)]
27 | struct Inner {
28 | remote_url: Url,
29 | refresh_interval: Duration,
30 | auth: HeaderValue,
31 | client: Client,
32 | repo: Arc>,
33 | should_stop: Arc>,
34 | }
35 |
36 | //TODO: graceful shutdown
37 | impl Synchronizer {
38 | pub fn new(
39 | remote_url: Url,
40 | refresh_interval: Duration,
41 | auth: HeaderValue,
42 | repo: Arc>,
43 | should_stop: Arc>,
44 | client: Client,
45 | ) -> Self {
46 | Self {
47 | inner: Arc::new(Inner {
48 | remote_url,
49 | refresh_interval,
50 | auth,
51 | client,
52 | repo,
53 | should_stop,
54 | }),
55 | }
56 | }
57 |
58 | pub fn start_sync(&self, start_wait: Option) {
59 | let should_stop = self.inner.should_stop.clone();
60 | let inner = self.inner.clone();
61 | let (tx, rx) = sync_channel(1);
62 | let start = Instant::now();
63 | let mut is_send = false;
64 | let interval_duration = inner.refresh_interval;
65 | let is_timeout = Self::init_timeout_fn(start_wait, interval_duration, start);
66 |
67 | tokio::spawn(async move {
68 | let mut interval = tokio::time::interval(inner.refresh_interval);
69 | loop {
70 | let result = inner.sync_now(SyncType::Polling).await;
71 |
72 | if let Some(r) = Self::should_send(result, &is_timeout, is_send) {
73 | is_send = true;
74 | let _ = tx.try_send(r);
75 | }
76 |
77 | if *should_stop.read() {
78 | break;
79 | }
80 | interval.tick().await;
81 | }
82 | });
83 |
84 | if start_wait.is_some() {
85 | let _ = rx.recv();
86 | }
87 | }
88 |
89 | pub async fn sync_now(&self, t: SyncType) -> Result<(), FPError> {
90 | self.inner.sync_now(t).await
91 | }
92 |
93 | #[cfg(test)]
94 | pub fn repository(&self) -> Arc> {
95 | self.inner.repo.clone()
96 | }
97 |
98 | fn init_timeout_fn(
99 | start_wait: Option,
100 | interval: Duration,
101 | start: Instant,
102 | ) -> Option bool + Send>> {
103 | match start_wait {
104 | Some(timeout) => Some(Box::new(move || start.elapsed() + interval > timeout)),
105 | None => None,
106 | }
107 | }
108 |
109 | fn should_send(
110 | result: Result<(), FPError>,
111 | is_timeout: &Option bool + Send>>,
112 | is_send: bool,
113 | ) -> Option> {
114 | if let Some(is_timeout) = is_timeout {
115 | match result {
116 | Ok(_) if !is_send => {
117 | return Some(Ok(()));
118 | }
119 | Err(e) if !is_send && is_timeout() => {
120 | error!("sync error: {}", e);
121 | return Some(Err(e));
122 | }
123 | Err(e) => error!("sync error: {}", e),
124 | _ => {}
125 | }
126 | }
127 | None
128 | }
129 | }
130 |
131 | impl Inner {
132 | pub async fn sync_now(&self, t: SyncType) -> Result<(), FPError> {
133 | let request = self
134 | .client
135 | .request(Method::GET, self.remote_url.clone())
136 | .header(AUTHORIZATION, self.auth.clone())
137 | .header(USER_AGENT, &*crate::USER_AGENT)
138 | .timeout(self.refresh_interval);
139 |
140 | trace!("sync_now {:?} {:?}", self.auth, t);
141 |
142 | //TODO: report failure
143 | match request.send().await {
144 | Err(e) => Err(FPError::HttpError(e.to_string())),
145 | Ok(resp) => {
146 | let status = resp.status();
147 | match status {
148 | StatusCode::OK => match resp.text().await {
149 | Err(e) => Err(FPError::HttpError(e.to_string())),
150 | Ok(body) => {
151 | debug!("sync body {:?}", body);
152 | match serde_json::from_str::>>(&body) {
153 | Err(e) => Err(FPError::JsonError(e.to_string())),
154 | Ok(r) => {
155 | // TODO: validate repo
156 | // TODO: diff change, notify subscriber
157 | debug!("sync success {:?}", r);
158 | let mut repo = self.repo.write();
159 | *repo = r;
160 | Ok(())
161 | }
162 | }
163 | }
164 | },
165 | _ => Err(FPError::HttpError(format!(
166 | "sync http failed: status code {}",
167 | status
168 | ))),
169 | }
170 | }
171 | }
172 | }
173 | }
174 |
175 | #[cfg(test)]
176 | mod tests {
177 | use super::*;
178 | use crate::{FPUser, SdkAuthorization};
179 | use axum::{
180 | response::{IntoResponse, Response},
181 | routing::get,
182 | Router, TypedHeader,
183 | };
184 |
185 | use feature_probe_server::{
186 | http::{serve_http, FpHttpHandler},
187 | realtime::RealtimeSocket,
188 | repo::SdkRepository,
189 | ServerConfig,
190 | };
191 | use http::{header, StatusCode};
192 | use std::{fs, net::SocketAddr, path::PathBuf};
193 |
194 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
195 | async fn test_sync() {
196 | let api_port = 19009;
197 | let server_port = 19010;
198 | let realtime_port = 19011;
199 | setup_mock_api(api_port).await;
200 | setup_fp_server(
201 | api_port,
202 | server_port,
203 | realtime_port,
204 | "client-sdk-key",
205 | "server-sdk-key",
206 | )
207 | .await;
208 | let syncer = build_synchronizer(server_port);
209 | syncer.start_sync(Some(Duration::from_secs(5)));
210 |
211 | tokio::time::sleep(Duration::from_millis(200)).await;
212 | let repo = syncer.repository();
213 | let repo = repo.read();
214 | assert!(repo.len() > 0)
215 | }
216 |
217 | fn build_synchronizer(port: u16) -> Synchronizer {
218 | let user = FPUser::new("123");
219 | let mut remote_url =
220 | Url::parse(&format!("http://127.0.0.1:{}/api/client-sdk/toggles", port)).unwrap();
221 | remote_url.set_query(Some(&format!("user={}", user.as_base64())));
222 | let refresh_interval = Duration::from_millis(1000);
223 | let auth = SdkAuthorization("client-sdk-key".to_owned()).encode();
224 | Synchronizer {
225 | inner: Arc::new(Inner {
226 | remote_url,
227 | refresh_interval,
228 | auth,
229 | client: Default::default(),
230 | repo: Default::default(),
231 | should_stop: Default::default(),
232 | }),
233 | }
234 | }
235 |
236 | async fn setup_mock_api(port: u16) {
237 | let app = Router::new().route("/api/server-sdk/toggles", get(server_sdk_toggles));
238 | let addr = SocketAddr::from(([0, 0, 0, 0], port));
239 | tokio::spawn(async move {
240 | let _ = axum::Server::bind(&addr)
241 | .serve(app.into_make_service())
242 | .await;
243 | });
244 | tokio::time::sleep(Duration::from_millis(100)).await;
245 | }
246 |
247 | async fn setup_fp_server(
248 | target_port: u16,
249 | server_port: u16,
250 | realtime_port: u16,
251 | client_sdk_key: &str,
252 | server_sdk_key: &str,
253 | ) -> Arc {
254 | let toggles_url = Url::parse(&format!(
255 | "http://127.0.0.1:{}/api/server-sdk/toggles",
256 | target_port
257 | ))
258 | .unwrap();
259 | let events_url =
260 | Url::parse(&format!("http://127.0.0.1:{}/api/events", target_port)).unwrap();
261 | let repo = SdkRepository::new(
262 | ServerConfig {
263 | toggles_url,
264 | analysis_url: None,
265 | keys_url: None,
266 | server_port,
267 | realtime_port,
268 | realtime_path: "/".to_owned(),
269 | events_url: events_url.clone(),
270 | refresh_interval: Duration::from_secs(1),
271 | client_sdk_key: Some(client_sdk_key.to_owned()),
272 | server_sdk_key: Some(server_sdk_key.to_owned()),
273 | },
274 | RealtimeSocket::serve(server_port + 100, "/"),
275 | );
276 | repo.sync(client_sdk_key.to_owned(), server_sdk_key.to_owned(), 1);
277 | let repo = Arc::new(repo);
278 | let feature_probe_server = FpHttpHandler {
279 | repo: repo.clone(),
280 | events_url,
281 | analysis_url: None,
282 | events_timeout: Duration::from_secs(1),
283 | http_client: Default::default(),
284 | };
285 | tokio::spawn(serve_http::(
286 | server_port,
287 | feature_probe_server,
288 | ));
289 | tokio::time::sleep(Duration::from_millis(100)).await;
290 | repo
291 | }
292 |
293 | async fn server_sdk_toggles(
294 | TypedHeader(SdkAuthorization(_sdk_key)): TypedHeader,
295 | ) -> Response {
296 | let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
297 | path.push("resources/fixtures/repo.json");
298 | let body = fs::read_to_string(path).unwrap();
299 | (
300 | StatusCode::OK,
301 | [(header::CONTENT_TYPE, "application/json")],
302 | body,
303 | )
304 | .into_response()
305 | }
306 | }
307 |
--------------------------------------------------------------------------------
/rust-core/src/user.rs:
--------------------------------------------------------------------------------
1 | use std::collections::HashMap;
2 |
3 | use serde::{Deserialize, Serialize};
4 |
5 | #[derive(Default, Debug, Deserialize, Serialize, Clone)]
6 | pub struct FPUser {
7 | pub key: String,
8 | attrs: HashMap,
9 | }
10 |
11 | impl FPUser {
12 | pub fn new>(key: T) -> Self {
13 | let key = key.into();
14 | FPUser {
15 | key,
16 | ..Default::default()
17 | }
18 | }
19 |
20 | pub fn with>(mut self, k: T, v: T) -> Self {
21 | self.attrs.insert(k.into(), v.into());
22 | self
23 | }
24 |
25 | pub fn with_attrs(mut self, attrs: impl Iterator
- ) -> Self {
26 | self.attrs.extend(attrs);
27 | self
28 | }
29 |
30 | pub fn get(&self, k: &str) -> Option<&String> {
31 | self.attrs.get(k)
32 | }
33 |
34 | pub fn get_all(&self) -> &HashMap {
35 | &self.attrs
36 | }
37 |
38 | pub fn as_base64(&self) -> String {
39 | let json_str = serde_json::to_string(&self).expect("must be valid");
40 | base64::encode(json_str)
41 | }
42 | }
43 |
44 | #[cfg(test)]
45 | mod tests {
46 | use super::*;
47 |
48 | #[test]
49 | fn test_user_with() {
50 | let u = FPUser::new("key").with("name", "bob").with("phone", "123");
51 | assert_eq!(u.key, "key");
52 | assert_eq!(u.get("name"), Some(&"bob".to_owned()));
53 | assert_eq!(u.get("phone"), Some(&"123".to_owned()));
54 | assert_eq!(u.get_all().len(), 2);
55 | }
56 |
57 | #[test]
58 | fn test_user_with_attrs() {
59 | let mut attrs: HashMap = Default::default();
60 | attrs.insert("name".to_owned(), "bob".to_owned());
61 | attrs.insert("phone".to_owned(), "123".to_owned());
62 | let u = FPUser::new("key").with_attrs(attrs.into_iter());
63 | assert_eq!(u.get_all().len(), 2);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/rust-core/tests/integration_test.rs:
--------------------------------------------------------------------------------
1 | use axum::{
2 | response::{IntoResponse, Response},
3 | routing::get,
4 | Router, TypedHeader,
5 | };
6 |
7 | use feature_probe_mobile_sdk_core::{FPConfig, FPUser, FeatureProbe, SdkAuthorization, Url};
8 | use feature_probe_server::{
9 | http::{serve_http, FpHttpHandler},
10 | realtime::RealtimeSocket,
11 | repo::SdkRepository,
12 | ServerConfig,
13 | };
14 | use http::{header, StatusCode};
15 | use std::{fs, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
16 |
17 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
18 | async fn integration_test() {
19 | let port = 19011;
20 | let server_port = 19012;
21 | let realtime_port = 10913;
22 | setup_mock_api(port).await;
23 | setup_fp_server(
24 | port,
25 | server_port,
26 | realtime_port,
27 | "client-sdk-key",
28 | "server-sdk-key",
29 | )
30 | .await;
31 |
32 | let toggles_url = format!("http://127.0.0.1:{}/api/client-sdk/toggles", server_port)
33 | .parse()
34 | .unwrap();
35 | let events_url = format!("http://127.0.0.1:{}/api/events", server_port)
36 | .parse()
37 | .unwrap();
38 |
39 | let realtime_url = format!("http://127.0.0.1:{}", realtime_port)
40 | .parse()
41 | .unwrap();
42 |
43 | let user = FPUser::new("some-user-key");
44 | let fp = FeatureProbe::new(
45 | FPConfig {
46 | toggles_url,
47 | events_url,
48 | realtime_url,
49 | client_sdk_key: "client-sdk-key".to_owned(),
50 | refresh_interval: Duration::from_millis(100),
51 | start_wait: Some(Duration::from_secs(3)),
52 | },
53 | user,
54 | );
55 |
56 | assert!(fp.bool_value("bool_toggle", false));
57 |
58 | let detail = fp.bool_detail("bool_toggle", false);
59 | assert!(detail.value);
60 | assert_eq!(detail.version, Some(1));
61 | assert_eq!(detail.rule_index, None);
62 | let reason = detail.reason;
63 | assert!(reason.contains("default"));
64 | }
65 |
66 | async fn setup_mock_api(port: u16) {
67 | let app = Router::new().route("/api/server-sdk/toggles", get(server_sdk_toggles));
68 | let addr = SocketAddr::from(([0, 0, 0, 0], port));
69 | tokio::spawn(async move {
70 | let _ = axum::Server::bind(&addr)
71 | .serve(app.into_make_service())
72 | .await;
73 | });
74 | tokio::time::sleep(Duration::from_millis(100)).await;
75 | }
76 |
77 | async fn setup_fp_server(
78 | target_port: u16,
79 | server_port: u16,
80 | realtime_port: u16,
81 | client_sdk_key: &str,
82 | server_sdk_key: &str,
83 | ) -> Arc {
84 | let toggles_url = Url::parse(&format!(
85 | "http://127.0.0.1:{}/api/server-sdk/toggles",
86 | target_port
87 | ))
88 | .unwrap();
89 |
90 | let events_url = Url::parse(&format!("http://127.0.0.1:{}/api/events", target_port)).unwrap();
91 | let repo = SdkRepository::new(
92 | ServerConfig {
93 | toggles_url,
94 | analysis_url: None,
95 | server_port,
96 | realtime_port,
97 | realtime_path: "/".to_owned(),
98 | keys_url: None,
99 | events_url: events_url.clone(),
100 | refresh_interval: Duration::from_secs(1),
101 | client_sdk_key: Some(client_sdk_key.to_owned()),
102 | server_sdk_key: Some(server_sdk_key.to_owned()),
103 | },
104 | RealtimeSocket::serve(realtime_port, "/"),
105 | );
106 | repo.sync(client_sdk_key.to_owned(), server_sdk_key.to_owned(), 1);
107 | let repo = Arc::new(repo);
108 | let feature_probe_server = FpHttpHandler {
109 | repo: repo.clone(),
110 | events_url,
111 | analysis_url: None,
112 | events_timeout: Duration::from_secs(1),
113 | http_client: Default::default(),
114 | };
115 | tokio::spawn(serve_http::(
116 | server_port,
117 | feature_probe_server,
118 | ));
119 | tokio::time::sleep(Duration::from_millis(100)).await;
120 | repo
121 | }
122 |
123 | async fn server_sdk_toggles(
124 | TypedHeader(SdkAuthorization(_sdk_key)): TypedHeader,
125 | ) -> Response {
126 | let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
127 | path.push("resources/fixtures/repo.json");
128 | let body = fs::read_to_string(path).unwrap();
129 | (
130 | StatusCode::OK,
131 | [(header::CONTENT_TYPE, "application/json")],
132 | body,
133 | )
134 | .into_response()
135 | }
136 |
--------------------------------------------------------------------------------
/rust-toolchain.toml:
--------------------------------------------------------------------------------
1 | [toolchain]
2 | channel = "nightly"
3 | components = [ "cargo", "rustfmt" ]
4 |
--------------------------------------------------------------------------------
/rust-uniffi/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "fp-mobile-uniffi"
3 | version = "2.0.2"
4 | edition = "2021"
5 |
6 | [lib]
7 | name = "featureprobe_ffi"
8 | crate-type = ["cdylib", "staticlib"]
9 |
10 | [dependencies]
11 | serde = { version = "1.0", features = ["derive"] }
12 | serde_json = "1.0"
13 | feature_probe_mobile_sdk_core = { path = "../rust-core" }
14 | parking_lot = { version = "0.12", features = ["serde"] }
15 | tracing = "0.1"
16 | tokio = { version = "1", features = ["full"] }
17 | lazy_static = "1.4"
18 |
19 | uniffi_macros = "0.21"
20 | uniffi = { version = "0.21", features = ["builtin-bindgen"] }
21 |
22 | [build-dependencies]
23 | uniffi_build = { version = "0.21", features = ["builtin-bindgen"] }
24 |
25 |
--------------------------------------------------------------------------------
/rust-uniffi/build.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | uniffi_build::generate_scaffolding("./src/featureprobe.udl").unwrap();
3 | }
4 |
--------------------------------------------------------------------------------
/rust-uniffi/src/featureprobe.udl:
--------------------------------------------------------------------------------
1 | namespace featureprobe { };
2 |
3 | interface FeatureProbe {
4 | constructor(FPConfig config, FPUser user);
5 |
6 | [Name=new_for_test]
7 | constructor(string toggles);
8 |
9 | void close();
10 |
11 | boolean bool_value([ByRef] string key, boolean default_value);
12 | FPBoolDetail bool_detail([ByRef] string key, boolean default_value);
13 |
14 | double number_value([ByRef] string key, double default_value);
15 | FPNumDetail number_detail([ByRef] string key, double default_value);
16 |
17 | string string_value([ByRef] string key, string default_value);
18 | FPStrDetail string_detail([ByRef] string key, string default_value);
19 |
20 | string json_value([ByRef] string key, string default_value);
21 | FPJsonDetail json_detail([ByRef] string key, string default_value);
22 |
23 | void track([ByRef] string event, optional double? value = null);
24 | };
25 |
26 | interface FPUser {
27 | constructor();
28 | void stable_rollout(string key);
29 | void with(string key, string value);
30 | };
31 |
32 | interface FPUrl {};
33 |
34 | interface FPUrlBuilder {
35 | constructor(string remote_url);
36 | FPUrl? build();
37 | };
38 |
39 | interface FPConfig {
40 | constructor(
41 | FPUrl remote_url,
42 | string client_sdk_key,
43 | u32 refresh_interval,
44 | u32 start_wait);
45 | };
46 |
47 | dictionary FPBoolDetail {
48 | boolean value;
49 | u16? rule_index;
50 | u64? version;
51 | string reason;
52 | };
53 |
54 | dictionary FPNumDetail {
55 | double value;
56 | u16? rule_index;
57 | u64? version;
58 | string reason;
59 | };
60 |
61 | dictionary FPStrDetail {
62 | string value;
63 | u16? rule_index;
64 | u64? version;
65 | string reason;
66 | };
67 |
68 | dictionary FPJsonDetail {
69 | string value;
70 | u16? rule_index;
71 | u64? version;
72 | string reason;
73 | };
74 |
--------------------------------------------------------------------------------
/rust-uniffi/src/lib.rs:
--------------------------------------------------------------------------------
1 | use feature_probe_mobile_sdk_core::FPConfig as CoreFPConfig;
2 | use feature_probe_mobile_sdk_core::FPDetail;
3 | use feature_probe_mobile_sdk_core::FPUser as CoreFPUser;
4 | use feature_probe_mobile_sdk_core::FeatureProbe as CoreFeatureProbe;
5 | use feature_probe_mobile_sdk_core::Url;
6 | use lazy_static::lazy_static;
7 | use parking_lot::Mutex;
8 | use serde::Serialize;
9 | use serde_json::Value;
10 | use std::time::Duration;
11 | use std::time::SystemTime;
12 | use std::time::UNIX_EPOCH;
13 | use std::{collections::HashMap, sync::Arc};
14 | use tokio::runtime::{Builder, Runtime};
15 |
16 | lazy_static! {
17 | pub static ref TOKIO_RUNTIME: Runtime = Builder::new_multi_thread()
18 | .enable_all()
19 | .worker_threads(4)
20 | .thread_name("featureprobe")
21 | .build()
22 | .expect("can not start tokio runtime");
23 | }
24 |
25 | struct FeatureProbe {
26 | core: CoreFeatureProbe,
27 | }
28 |
29 | impl FeatureProbe {
30 | fn new(config: Arc, user: Arc) -> Self {
31 | let _enter = TOKIO_RUNTIME.enter();
32 | let c_user = CoreFPUser::new(user.key.lock().clone())
33 | .with_attrs(user.attrs.lock().clone().into_iter());
34 |
35 | let c_config = CoreFPConfig {
36 | toggles_url: config.remote_url.toggles_url.clone(),
37 | events_url: config.remote_url.events_url.clone(),
38 | realtime_url: config.remote_url.realtime_url.clone(),
39 | client_sdk_key: config.client_sdk_key.clone(),
40 | start_wait: Some(Duration::from_secs(config.start_wait as u64)),
41 | refresh_interval: Duration::from_secs(config.refresh_interval as u64),
42 | };
43 |
44 | let core = CoreFeatureProbe::new(c_config, c_user);
45 | FeatureProbe { core }
46 | }
47 |
48 | fn close(&self) {
49 | self.core.close()
50 | }
51 |
52 | fn bool_value(&self, toggle: &str, default_value: bool) -> bool {
53 | self.core.bool_value(toggle, default_value)
54 | }
55 |
56 | fn bool_detail(&self, toggle: &str, default_value: bool) -> FPBoolDetail {
57 | let d = self.core.bool_detail(toggle, default_value);
58 | FPBoolDetail {
59 | value: d.value,
60 | rule_index: d.rule_index.map(|f| f as u16),
61 | version: d.version,
62 | reason: d.reason,
63 | }
64 | }
65 |
66 | fn number_value(&self, toggle: &str, default_value: f64) -> f64 {
67 | self.core.number_value(toggle, default_value)
68 | }
69 |
70 | fn number_detail(&self, toggle: &str, default_value: f64) -> FPNumDetail {
71 | let d = self.core.number_detail(toggle, default_value);
72 | FPNumDetail {
73 | value: d.value,
74 | rule_index: d.rule_index.map(|f| f as u16),
75 | version: d.version,
76 | reason: d.reason,
77 | }
78 | }
79 |
80 | fn string_value(&self, toggle: &str, default_value: String) -> String {
81 | self.core.string_value(toggle, default_value)
82 | }
83 |
84 | fn string_detail(&self, toggle: &str, default_value: String) -> FPStrDetail {
85 | let d = self.core.string_detail(toggle, default_value);
86 | FPStrDetail {
87 | value: d.value,
88 | rule_index: d.rule_index.map(|f| f as u16),
89 | version: d.version,
90 | reason: d.reason,
91 | }
92 | }
93 |
94 | fn json_value(&self, toggle: &str, default_value: String) -> String {
95 | let default_value =
96 | serde_json::from_str(&default_value).expect("default_value is not json");
97 | let v = self.core.json_value(toggle, default_value);
98 | serde_json::to_string(&v).expect("invalid json")
99 | }
100 |
101 | fn json_detail(&self, toggle: &str, default_value: String) -> FPJsonDetail {
102 | let default_value =
103 | serde_json::from_str(&default_value).expect("default_value is not json");
104 | let d = self.core.json_detail(toggle, default_value);
105 | let value = serde_json::to_string(&d.value).expect("invalid json");
106 | FPJsonDetail {
107 | value,
108 | rule_index: d.rule_index.map(|f| f as u16),
109 | version: d.version,
110 | reason: d.reason,
111 | }
112 | }
113 |
114 | fn track(&self, event: &str, value: Option) {
115 | self.core.track_event(event, value);
116 | }
117 |
118 | fn new_for_test(toggles: String) -> Self {
119 | let m: HashMap =
120 | serde_json::from_str(&toggles).expect("invalid default toggles json");
121 |
122 | let repo: HashMap> = m
123 | .into_iter()
124 | .map(|(k, value)| {
125 | (
126 | k,
127 | FPDetail:: {
128 | value,
129 | ..Default::default()
130 | },
131 | )
132 | })
133 | .collect();
134 |
135 | let core = CoreFeatureProbe::new_with(repo);
136 | FeatureProbe { core }
137 | }
138 | }
139 |
140 | #[derive(Debug, Default)]
141 | pub struct FPBoolDetail {
142 | pub value: bool,
143 | pub rule_index: Option,
144 | pub version: Option,
145 | pub reason: String,
146 | }
147 |
148 | #[derive(Debug, Default)]
149 | pub struct FPNumDetail {
150 | pub value: f64,
151 | pub rule_index: Option,
152 | pub version: Option,
153 | pub reason: String,
154 | }
155 |
156 | #[derive(Debug, Default)]
157 | pub struct FPStrDetail {
158 | pub value: String,
159 | pub rule_index: Option,
160 | pub version: Option,
161 | pub reason: String,
162 | }
163 |
164 | #[derive(Debug, Default)]
165 | pub struct FPJsonDetail {
166 | pub value: String,
167 | pub rule_index: Option,
168 | pub version: Option,
169 | pub reason: String,
170 | }
171 |
172 | #[derive(Debug)]
173 | pub struct FPUrlBuilder {
174 | remote_url: String,
175 | toggles_url: Option,
176 | events_url: Option,
177 | }
178 |
179 | impl FPUrlBuilder {
180 | pub fn new(remote_url: String) -> Self {
181 | Self {
182 | remote_url,
183 | toggles_url: None,
184 | events_url: None,
185 | }
186 | }
187 |
188 | pub fn new_urls(
189 | remote_url: String,
190 | toggles_url: Option,
191 | events_url: Option,
192 | ) -> Self {
193 | Self {
194 | remote_url,
195 | toggles_url,
196 | events_url,
197 | }
198 | }
199 |
200 | pub fn build(&self) -> Option> {
201 | let remote_url = if !self.remote_url.ends_with('/') {
202 | format!("{}/", self.remote_url)
203 | } else {
204 | self.remote_url.clone()
205 | };
206 |
207 | let realtime_url = format!("{}/realtime", remote_url);
208 |
209 | let toggles_url = match self.toggles_url {
210 | None => format!("{}api/client-sdk/toggles", remote_url),
211 | Some(ref url) => url.clone(),
212 | };
213 |
214 | let events_url = match self.events_url {
215 | None => format!("{}api/events", remote_url),
216 | Some(ref url) => url.clone(),
217 | };
218 |
219 | let toggles_url = Url::parse(&toggles_url).ok()?;
220 | let events_url = Url::parse(&events_url).ok()?;
221 | let realtime_url = Url::parse(&realtime_url).ok()?;
222 |
223 | Some(Arc::new(FPUrl {
224 | toggles_url,
225 | events_url,
226 | realtime_url,
227 | }))
228 | }
229 | }
230 |
231 | #[derive(Debug)]
232 | pub struct FPUrl {
233 | pub toggles_url: Url,
234 | pub events_url: Url,
235 | pub realtime_url: Url,
236 | }
237 |
238 | #[derive(Debug)]
239 | pub struct FPConfig {
240 | pub remote_url: Arc,
241 | pub client_sdk_key: String,
242 | pub refresh_interval: u32,
243 | pub start_wait: u32,
244 | }
245 |
246 | impl FPConfig {
247 | fn new(
248 | remote_url: Arc,
249 | client_sdk_key: String,
250 | refresh_interval: u32,
251 | start_wait: u32,
252 | ) -> Self {
253 | FPConfig {
254 | remote_url,
255 | client_sdk_key,
256 | refresh_interval,
257 | start_wait,
258 | }
259 | }
260 | }
261 |
262 | #[derive(Default, Serialize, Debug)]
263 | struct FPUser {
264 | pub key: Mutex,
265 | pub attrs: Mutex>,
266 | }
267 |
268 | impl FPUser {
269 | fn new() -> Self {
270 | Self {
271 | key: Mutex::new(generate_key()),
272 | attrs: Default::default(),
273 | }
274 | }
275 |
276 | fn with(&self, key: String, value: String) {
277 | let mut attrs = self.attrs.lock();
278 | attrs.insert(key, value);
279 | }
280 |
281 | fn stable_rollout(&self, key: String) {
282 | let mut guard = self.key.lock();
283 | *guard = key;
284 | }
285 | }
286 |
287 | fn generate_key() -> String {
288 | let start = SystemTime::now();
289 | let since_the_epoch = start
290 | .duration_since(UNIX_EPOCH)
291 | .expect("Time went before epoch");
292 | format!("{}", since_the_epoch.as_micros())
293 | }
294 |
295 | uniffi_macros::include_scaffolding!("featureprobe");
296 |
--------------------------------------------------------------------------------
/rust-uniffi/tests/bindings/test.kts:
--------------------------------------------------------------------------------
1 | import com.featureprobe.mobile.*;
2 |
3 | val url = FpUrlBuilder("https://featureprobe.io/server").build()
4 | val user = FpUser()
5 | user.with("city", "1")
6 | val config = FpConfig(url!!, "client-1b31633671aa8be967697091b72d23da6bf858a7", 10u, 5u)
7 | val fp = FeatureProbe(config, user)
8 | fp.close()
9 |
10 | val toggle = fp.boolDetail("campaign_enable", true)
11 | println("toggle value is $toggle")
12 |
13 | val fp_for_test = FeatureProbe.newForTest("{ \"toggle_1\": true }")
14 | val is_true = fp_for_test.boolValue("toggle_1", false)
15 | assert(is_true == true)
16 |
17 | fp_for_test.track("event")
18 | fp_for_test.track("eventWithValue", 1.0)
19 |
--------------------------------------------------------------------------------
/rust-uniffi/tests/bindings/test.swift:
--------------------------------------------------------------------------------
1 | import featureprobe
2 |
3 | let url = FpUrlBuilder(remoteUrl: "https://featureprobe.io/server").build();
4 | let user = FpUser()
5 | user.with(key: "city", value: "1")
6 | let config = FpConfig(
7 | remoteUrl: url!,
8 | clientSdkKey: "client-1b31633671aa8be967697091b72d23da6bf858a7",
9 | refreshInterval: 10,
10 | startWait: 2
11 | )
12 | let fp = FeatureProbe(config: config, user: user)
13 | let toggle = fp.boolDetail(key: "campaign_enable", defaultValue: true)
14 | print("toogle value is \(toggle)")
15 | fp.close()
16 |
17 | let fp2 = FeatureProbe.newForTest(toggles: "{ \"toggle_1\": true }")
18 | let is_true = fp2.boolValue(key: "toggle_1", defaultValue: false)
19 | assert(is_true == true);
20 |
21 | fp2.track(event: "event")
22 | fp2.track(event: "eventWithValue", value: 1.0)
23 |
24 |
--------------------------------------------------------------------------------
/rust-uniffi/tests/test_generated_bindings.rs:
--------------------------------------------------------------------------------
1 | uniffi_macros::build_foreign_language_testcases!(
2 | ["src/featureprobe.udl",],
3 | ["tests/bindings/test.kts", "tests/bindings/test.swift",]
4 | );
5 |
--------------------------------------------------------------------------------
/rust-uniffi/uniffi.toml:
--------------------------------------------------------------------------------
1 | [bindings.kotlin]
2 | package_name = "com.featureprobe.mobile"
3 | cdylib_name = "featureprobe_ffi"
4 |
5 | [bindings.swift]
6 | cdylib_name = "featureprobe_ffi"
7 | module_name = "FeatureProbe"
--------------------------------------------------------------------------------
/sdk-android/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/sdk-android/README.md:
--------------------------------------------------------------------------------
1 | # FeatureProbe Android SDK
2 |
3 | ## How to use this SDK
4 |
5 | See [Android](https://docs.featureprobe.io/how-to/Client-Side%20SDKs/android-sdk/) SDK Doc for detail. [安卓](https://docs.featureprobe.io/zh-CN/how-to/Client-Side%20SDKs/android-sdk)
6 |
7 | ## How to build
8 |
9 | 0. make sure NDK version 21.3.6528147 is installed, and JNA jna.jar in $CLASSPATH
10 |
11 | 1. install uniffi codegen tool
12 |
13 | `cargo install --version 0.21 uniffi_bindgen`
14 |
15 | 2. install rust android target
16 |
17 | ```console
18 | rustup target add armv7-linux-androideabi # for arm
19 | rustup target add aarch64-apple-darwin # for darwin arm64 (if you have a M1 MacOS)
20 | rustup target add i686-linux-android # for x86
21 | rustup target add x86_64-linux-android
22 | rustup target add aarch64-linux-android
23 | ```
24 |
25 | 3. build android lib
26 |
27 | ./gradlew build
28 |
--------------------------------------------------------------------------------
/sdk-android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id 'com.android.application' version '7.1.3' apply false
4 | id 'com.android.library' version '7.1.3' apply false
5 | id 'org.jetbrains.kotlin.android' version '1.6.21' apply false
6 | }
7 |
8 | task clean(type: Delete) {
9 | delete rootProject.buildDir
10 | }
--------------------------------------------------------------------------------
/sdk-android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 |
25 | android.disableAutomaticComponentCreation=true
26 | POM_DESCRIPTION=FeatureProbe client Side SDK for Android
27 | POM_URL=https://github.com/FeatureProbe/client-sdk-mobile
28 | POM_SCM_URL=https://github.com/FeatureProbe/client-sdk-mobile
29 | POM_SCM_CONNECTION=scm:git:git@github.com:FeatureProbe/client-sdk-mobile.git
30 | POM_SCM_DEV_CONNECTION=scm:git@github.com:FeatureProbe/client-sdk-mobile.git
31 | POM_LICENCE_NAME=Apache License, Version 2.0
32 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
33 | POM_LICENCE_DIST=Apache 2.0
34 | POM_DEVELOPER_ID=SSebo
35 | POM_DEVELOPER_NAME=SSebo
--------------------------------------------------------------------------------
/sdk-android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/sdk-android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/sdk-android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri May 06 15:19:52 CST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/sdk-android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/sdk-android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/sdk-android/publish_aar.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven-publish'
2 | apply plugin: 'signing'
3 |
4 | task androidSourcesJar(type: Jar) {
5 | classifier = 'sources'
6 | from android.sourceSets.main.java.source
7 |
8 | exclude "**/R.class"
9 | exclude "**/BuildConfig.class"
10 | }
11 |
12 | ext {path=
13 | PUBLISH_GROUP_ID = 'com.featureprobe'
14 | PUBLISH_ARTIFACT_ID = 'client-sdk-android'
15 | PUBLISH_VERSION = '2.0.2' // update this version when release
16 | }
17 |
18 | ext["signing.keyId"] = System.getProperty("SIGN_KEYID")
19 | ext["signing.password"] = System.getProperty('SIGN_PASSWORD')
20 | ext["signing.secretKeyRingFile"] = './secring.gpg'
21 | ext["ossrhUsername"] = System.getProperty('OSSRH_USERNAME')
22 | ext["ossrhPassword"] = System.getProperty('OSSRH_PASSWORD')
23 |
24 | publishing {
25 | publications {
26 | release(MavenPublication) {
27 | println("publish-maven Log-------> PUBLISH_GROUP_ID: $PUBLISH_GROUP_ID; PUBLISH_ARTIFACT_ID: $PUBLISH_ARTIFACT_ID; PUBLISH_VERSION: $PUBLISH_VERSION")
28 | groupId PUBLISH_GROUP_ID
29 | artifactId PUBLISH_ARTIFACT_ID
30 | version PUBLISH_VERSION
31 |
32 | artifact("$buildDir/outputs/aar/sdk-release.aar")
33 | artifact androidSourcesJar
34 |
35 | pom {
36 | name = PUBLISH_ARTIFACT_ID
37 | description = 'FeatureProbe Server Side SDK for Android'
38 | url = 'https://github.com/FeatureProbe/client-sdk-mobile'
39 | licenses {
40 | license {
41 | name = 'Apache License, Version 2.0'
42 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
43 | }
44 | }
45 | developers {
46 | developer {
47 | id = 'SSebo'
48 | name = 'SSebo'
49 | }
50 | }
51 | scm {
52 | connection = 'scm:git@github.com:FeatureProbe/client-sdk-mobile.git'
53 | developerConnection = 'scm:git@github.com:FeatureProbe/client-sdk-mobile.git'
54 | url = 'https://github.com/FeatureProbe/client-sdk-mobile'
55 | }
56 |
57 | withXml {
58 | def dependenciesNode = asNode().appendNode('dependencies')
59 |
60 | project.configurations.implementation.allDependencies.each {
61 | def dependencyNode = dependenciesNode.appendNode('dependency')
62 | dependencyNode.appendNode('groupId', it.group)
63 | dependencyNode.appendNode('artifactId', it.name)
64 | dependencyNode.appendNode('version', it.version)
65 | }
66 | }
67 | }
68 | }
69 | }
70 | repositories {
71 | maven {
72 | name = "client-sdk-mobile"
73 | def releasesRepoUrl = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
74 | def snapshotsRepoUrl = "https://s01.oss.sonatype.org/content/repositories/snapshots/"
75 |
76 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
77 |
78 | credentials {
79 | username ossrhUsername
80 | password ossrhPassword
81 | }
82 | }
83 | }
84 | }
85 | signing {
86 | sign publishing.publications
87 | }
88 |
--------------------------------------------------------------------------------
/sdk-android/sdk/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/sdk-android/sdk/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'org.jetbrains.kotlin.android'
4 | id "org.mozilla.rust-android-gradle.rust-android" version "0.9.2"
5 | }
6 |
7 | android {
8 | ndkVersion "21.3.6528147"
9 | compileSdk 31
10 |
11 | defaultConfig {
12 | minSdk 21
13 | targetSdk 31
14 |
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | consumerProguardFiles "consumer-rules.pro"
17 | buildConfigField("String", "LIBRARY_VERSION", "\"1.2.0\"")
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 |
27 | sourceSets {
28 | test.jniLibs.srcDirs += "$buildDir/rustJniLibs/android"
29 | }
30 |
31 | compileOptions {
32 | sourceCompatibility JavaVersion.VERSION_1_8
33 | targetCompatibility JavaVersion.VERSION_1_8
34 | }
35 | kotlinOptions {
36 | jvmTarget = '1.8'
37 | }
38 | }
39 |
40 | cargo {
41 | // The directory of the Cargo.toml to build.
42 | module = '../../rust-uniffi'
43 | // The Android NDK API level to target.
44 | apiLevel = 21
45 |
46 | // Where Cargo writes its outputs.
47 | targetDirectory = '../../target'
48 |
49 | libname = 'featureprobe_ffi'
50 |
51 | // Perform release builds (which should have debug info, due to
52 | // `debug = true` in Cargo.toml).
53 | profile = "release"
54 |
55 | targets = [ 'arm',
56 | 'arm64',
57 | 'x86_64',
58 | 'x86',
59 | ]
60 |
61 | rustupChannel = "nightly"
62 |
63 | extraCargoBuildArguments = ['-Z', 'build-std=std,panic_abort']
64 |
65 | verbose = true
66 |
67 | }
68 |
69 | dependencies {
70 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.20"
71 | implementation "net.java.dev.jna:jna:5.7.0@aar"
72 | testImplementation 'junit:junit:4.13.2'
73 | }
74 |
75 | afterEvaluate {
76 | // The `cargoBuild` task isn't available until after evaluation.
77 | android.libraryVariants.all { variant ->
78 | def productFlavor = ""
79 | variant.productFlavors.each {
80 | productFlavor += "${it.name.capitalize()}"
81 | }
82 | def buildType = "${variant.buildType.name.capitalize()}"
83 | tasks["merge${productFlavor}${buildType}JniLibFolders"].dependsOn(tasks["cargoBuild"])
84 | }
85 | }
86 |
87 | ext.configureUniFFIBindgen = { udlFilePath ->
88 | android.libraryVariants.all { variant ->
89 | def uniffiGeneratedPath = "generated/source/uniffi/${variant.name}/java"
90 | def t = tasks.register("generate${variant.name.capitalize()}UniFFIBindings", Exec) {
91 | workingDir project.rootDir
92 | // should run this cmd first : cargo install uniffi_bindgen
93 | commandLine '/usr/bin/env', 'uniffi-bindgen', 'generate', "${project.projectDir}/${udlFilePath}", '--language', 'kotlin', '--out-dir', "${buildDir}/${uniffiGeneratedPath}"
94 | outputs.dir "${buildDir}/${uniffiGeneratedPath}"
95 | // Re-generate if the interface definition changes.
96 | inputs.file "${project.projectDir}/${udlFilePath}"
97 | }
98 | variant.registerJavaGeneratingTask(t.get(), new File(buildDir, uniffiGeneratedPath))
99 | }
100 | }
101 |
102 | // should run this cmd first : cargo install uniffi_bindgen
103 | ext.configureUniFFIBindgen("../../rust-uniffi/src/featureprobe.udl")
104 |
105 | apply from: "../publish_aar.gradle"
106 |
--------------------------------------------------------------------------------
/sdk-android/sdk/consumer-rules.pro:
--------------------------------------------------------------------------------
1 | # feature probe sdk
2 | -keep class com.featureprobe.mobile.* { *; }
3 |
4 | # jna
5 | -dontwarn java.awt.*
6 | -keep class com.sun.jna.* { *; }
7 | -keepclassmembers class * extends com.sun.jna.* { public *; }
--------------------------------------------------------------------------------
/sdk-android/sdk/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/sdk-android/sdk/secring.gpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FeatureProbe/client-sdk-mobile/8cdca5d1c74d118afd49e4b8c790e26a7413dc49/sdk-android/sdk/secring.gpg
--------------------------------------------------------------------------------
/sdk-android/sdk/src/androidTest/java/com/featureprobe/sdk/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.sdk
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.featureprobe.sdk.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/sdk-android/sdk/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/sdk-android/sdk/src/test/java/com/featureprobe/sdk/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.featureprobe.sdk
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/sdk-android/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "AndroidSdk"
16 | include ':sdk'
17 |
--------------------------------------------------------------------------------
/sdk-ios/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /.build
3 | /Packages
4 | /*.xcodeproj
5 | xcuserdata/
6 | DerivedData/
7 | .swiftpm/config/registries.json
8 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
9 | .netrc
10 | FeatureProbeFFI.xcframework*
--------------------------------------------------------------------------------
/sdk-ios/FeatureProbe.podspec:
--------------------------------------------------------------------------------
1 | Pod::Spec.new do |s|
2 | s.name = 'FeatureProbe'
3 | s.version = '2.2.0'
4 | s.license = { :type => 'MIT' }
5 | s.homepage = 'https://github.com/FeatureProbe/FeatureProbe'
6 | s.authors = { 'featureprobe' => 'developer@featureprobe.com' }
7 | s.summary = 'iOS feature probe SDK'
8 | s.source = { :git => 'https://github.com/FeatureProbe/client-sdk-ios.git', :tag => s.version }
9 | s.source_files = 'Sources/**/*.swift'
10 |
11 | s.platform = :ios, '10.0'
12 | s.pod_target_xcconfig = { 'VALID_ARCHS' => 'x86_64 arm64' }
13 | s.swift_versions = ['4.0', '4.2', '5.0', '5.5']
14 | s.vendored_frameworks = "FeatureProbeFFI.xcframework"
15 | s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
16 | s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
17 | end
18 |
--------------------------------------------------------------------------------
/sdk-ios/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | AvailableLibraries
6 |
7 |
8 | LibraryIdentifier
9 | ios-arm64
10 | LibraryPath
11 | FeatureProbeFFI.framework
12 | SupportedArchitectures
13 |
14 | arm64
15 |
16 | SupportedPlatform
17 | ios
18 |
19 |
20 | LibraryIdentifier
21 | ios-arm64_x86_64-simulator
22 | LibraryPath
23 | FeatureProbeFFI.framework
24 | SupportedArchitectures
25 |
26 | arm64
27 | x86_64
28 |
29 | SupportedPlatform
30 | ios
31 | SupportedPlatformVariant
32 | simulator
33 |
34 |
35 | CFBundlePackageType
36 | XFWK
37 | XCFrameworkFormatVersion
38 | 1.0
39 |
40 |
41 |
--------------------------------------------------------------------------------
/sdk-ios/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 FeatureProbe
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/sdk-ios/ObjcFeatureProbe.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 |
3 | @objc(FpConfig)
4 | public final class OFpConfig: NSObject {
5 | var config: FpConfig
6 |
7 | @objc public init(remoteUrl: OFpUrl, clientSdkKey: String, refreshInterval: UInt32, startWait: UInt32) {
8 | let remoteUrl = remoteUrl._url
9 | config = FpConfig(remoteUrl: remoteUrl, clientSdkKey: clientSdkKey, refreshInterval: refreshInterval, startWait: startWait)
10 | }
11 |
12 | }
13 |
14 | @objc(FeatureProbe)
15 | public final class OcFeatureProbe: NSObject {
16 | var fp: FeatureProbe
17 |
18 | @objc public init(config: OFpConfig, user: OFpUser) {
19 | let config = config.config
20 | let user = user.user
21 | fp = FeatureProbe(config: config, user: user)
22 | }
23 |
24 | @objc public init(testJson: String) {
25 | fp = FeatureProbe.newForTest(toggles: testJson)
26 | }
27 |
28 | @objc public func boolValue(key: String, defaultValue: Bool) -> Bool {
29 | fp.boolValue(key: key, defaultValue: defaultValue)
30 | }
31 |
32 | @objc public func boolDetail(key: String, defaultValue: Bool) -> OFpBoolDetail {
33 | let d = fp.boolDetail(key: key, defaultValue: defaultValue)
34 | return OFpBoolDetail(detail: d)
35 | }
36 |
37 | @objc public func numberValue(key: String, defaultValue: Double) -> Double {
38 | fp.numberValue(key: key, defaultValue: defaultValue)
39 | }
40 |
41 | @objc public func numberDetail(key: String, defaultValue: Double) -> OFpNumberDetail {
42 | let d = fp.numberDetail(key: key, defaultValue: defaultValue)
43 | return OFpNumberDetail(detail: d)
44 | }
45 |
46 | @objc public func stringValue(key: String, defaultValue: String) -> String {
47 | fp.stringValue(key: key, defaultValue: defaultValue)
48 | }
49 |
50 | @objc public func stringDetail(key: String, defaultValue: String) -> OFpStringDetail {
51 | let d = fp.stringDetail(key: key, defaultValue: defaultValue)
52 | return OFpStringDetail(detail: d)
53 | }
54 |
55 | @objc public func jsonValue(key: String, defaultValue: String) -> String {
56 | fp.jsonValue(key: key, defaultValue: defaultValue)
57 | }
58 |
59 | @objc public func jsonDetail(key: String, defaultValue: String) -> OFpJsonDetail {
60 | let d = fp.jsonDetail(key: key, defaultValue: defaultValue)
61 | return OFpJsonDetail(detail: d)
62 | }
63 |
64 | @objc public func track(event: String) {
65 | fp.track(event: event)
66 | }
67 |
68 | @objc public func track(event: String, value: Double) {
69 | fp.track(event: event, value: value)
70 | }
71 |
72 | @objc public func close() {
73 | fp.close()
74 | }
75 |
76 | }
77 |
78 | @objc(FpUser)
79 | public final class OFpUser: NSObject {
80 | var user: FpUser
81 |
82 | @objc override public init() {
83 | user = FpUser()
84 | }
85 |
86 | @objc public func with(key: String, value: String) {
87 | user.with(key: key, value: value)
88 | }
89 |
90 | @objc public func stableRollout(key: String) {
91 | user.stableRollout(key: key)
92 | }
93 | }
94 |
95 | @objc(FpUrl)
96 | public final class OFpUrl: NSObject {
97 | var _url: FpUrl
98 |
99 | public init(url: FpUrl) {
100 | _url = url
101 | }
102 | }
103 |
104 | @objc(FpUrlBuilder)
105 | public final class OFpUrlBuilder: NSObject {
106 | var builder: FpUrlBuilder
107 |
108 | @objc public init(remoteUrl: String) {
109 | builder = FpUrlBuilder(remoteUrl: remoteUrl)
110 | }
111 |
112 | @objc public func build() -> OFpUrl? {
113 | let url = builder.build()
114 | if url == nil {
115 | return nil
116 | }
117 | return OFpUrl(url: url!)
118 | }
119 |
120 | }
121 |
122 | @objc(FpBoolDetail)
123 | public final class OFpBoolDetail: NSObject {
124 | var _detail: FpBoolDetail
125 |
126 | public init(detail: FpBoolDetail) {
127 | _detail = detail
128 | }
129 |
130 | @objc public var value: Bool {
131 | _detail.value
132 | }
133 |
134 | @objc public var ruleIndex: NSNumber {
135 | if _detail.ruleIndex == nil {
136 | return -1
137 | } else {
138 | return _detail.ruleIndex! as NSNumber
139 | }
140 | }
141 |
142 | @objc public var version: NSNumber {
143 | if _detail.version == nil {
144 | return -1
145 | } else {
146 | return _detail.version! as NSNumber
147 | }
148 | }
149 |
150 | @objc public var reason: String {
151 | _detail.reason
152 | }
153 | }
154 |
155 | @objc(FpNumberDetail)
156 | public final class OFpNumberDetail: NSObject {
157 | var _detail: FpNumDetail
158 |
159 | public init(detail: FpNumDetail) {
160 | _detail = detail
161 | }
162 |
163 | @objc public var value: Double {
164 | _detail.value
165 | }
166 |
167 | @objc public var ruleIndex: NSNumber {
168 | if _detail.ruleIndex == nil {
169 | return -1
170 | } else {
171 | return _detail.ruleIndex! as NSNumber
172 | }
173 | }
174 |
175 | @objc public var version: NSNumber {
176 | if _detail.version == nil {
177 | return -1
178 | } else {
179 | return _detail.version! as NSNumber
180 | }
181 | }
182 |
183 | @objc public var reason: String {
184 | _detail.reason
185 | }
186 | }
187 |
188 | @objc(FpStringDetail)
189 | public final class OFpStringDetail: NSObject {
190 | var _detail: FpStrDetail
191 |
192 | public init(detail: FpStrDetail) {
193 | _detail = detail
194 | }
195 |
196 | @objc public var value: String {
197 | _detail.value
198 | }
199 |
200 | @objc public var ruleIndex: NSNumber {
201 | if _detail.ruleIndex == nil {
202 | return -1
203 | } else {
204 | return _detail.ruleIndex! as NSNumber
205 | }
206 | }
207 |
208 | @objc public var version: NSNumber {
209 | if _detail.version == nil {
210 | return -1
211 | } else {
212 | return _detail.version! as NSNumber
213 | }
214 | }
215 |
216 | @objc public var reason: String {
217 | _detail.reason
218 | }
219 | }
220 |
221 | @objc(FpJsonDetail)
222 | public final class OFpJsonDetail: NSObject {
223 | var _detail: FpJsonDetail
224 |
225 | public init(detail: FpJsonDetail) {
226 | _detail = detail
227 | }
228 |
229 | @objc public var value: String {
230 | _detail.value
231 | }
232 |
233 | @objc public var ruleIndex: NSNumber {
234 | if _detail.ruleIndex == nil {
235 | return -1
236 | } else {
237 | return _detail.ruleIndex! as NSNumber
238 | }
239 | }
240 |
241 | @objc public var version: NSNumber {
242 | if _detail.version == nil {
243 | return -1
244 | } else {
245 | return _detail.version! as NSNumber
246 | }
247 | }
248 |
249 | @objc public var reason: String {
250 | _detail.reason
251 | }
252 | }
253 |
--------------------------------------------------------------------------------
/sdk-ios/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version: 5.4
2 | import PackageDescription
3 |
4 | let package = Package(
5 | name: "FeatureProbe",
6 | platforms: [.iOS(.v9)],
7 | products: [
8 | // Products define the executables and libraries a package produces, and make them visible to other packages.
9 | .library(
10 | name: "FeatureProbe",
11 | targets: ["FeatureProbe"])
12 | ],
13 | dependencies: [
14 | ],
15 | targets: [
16 | // Targets are the basic building blocks of a package. A target can define a module or a test suite.
17 | // Targets can depend on other targets in this package, and on products in packages this package depends on.
18 | .binaryTarget(
19 | name: "FeatureProbeFFI",
20 | path: "./FeatureProbeFFI.xcframework"
21 | ),
22 | .target(
23 | name: "FeatureProbe",
24 | dependencies: ["FeatureProbeFFI"]
25 | )
26 | ]
27 | )
28 |
--------------------------------------------------------------------------------
/sdk-ios/README.md:
--------------------------------------------------------------------------------
1 | # FeatureProbe iOS-SDK
2 |
3 | ## How to use this SDK
4 |
5 | See [iOS](https://docs.featureprobe.io/how-to/Client-Side%20SDKs/ios-sdk/) SDK Doc for detail. [苹果](https://docs.featureprobe.io/zh-CN/how-to/Client-Side%20SDKs/ios-sdk/)
6 |
7 | ## How to build
8 |
9 | build from repo: `git@github.com:FeatureProbe/client-sdk-mobile.git`
10 |
11 | 1. install uniffi codegen tool
12 |
13 | `cargo install --version 0.21 uniffi_bindgen`
14 |
15 | 2. install rust android target
16 |
17 | ```console
18 | rustup target add aarch64-apple-ios
19 | rustup target add aarch64-apple-ios-sim
20 | rustup target add x86_64-apple-ios
21 | ```
22 |
23 | 3. build xcframework
24 |
25 | `./build-xcframework.sh`
26 |
27 | 4. push to git
28 |
29 | ```
30 | cd client-sdk-ios
31 | git commit -m 'xxx'
32 | git push origin master
33 | ```
34 |
35 | ## Contributing
36 |
37 | We are working on continue evolving FeatureProbe core, making it flexible and easier to use.
38 | Development of FeatureProbe happens in the open on GitHub, and we are grateful to the
39 | community for contributing bugfixes and improvements.
40 |
41 | Please read [CONTRIBUTING](https://github.com/FeatureProbe/featureprobe/blob/master/CONTRIBUTING.md)
42 | for details on our code of conduct, and the process for taking part in improving FeatureProbe.
43 |
--------------------------------------------------------------------------------
/sdk-ios/build-xcframework.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | #
3 | # This script builds the Rust crate in its directory into a staticlib XCFramework for iOS.
4 |
5 | BUILD_PROFILE="release"
6 | FRAMEWORK_NAME="FeatureProbeFFI"
7 |
8 | while [[ "$#" -gt 0 ]]; do case $1 in
9 | --build-profile) BUILD_PROFILE="$2"; shift;shift;;
10 | --framework-name) FRAMEWORK_NAME="$2"; shift;shift;;
11 | *) echo "Unknown parameter: $1"; exit 1;
12 | esac; done
13 |
14 | THIS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
15 | PARENT_DIR="$( dirname "$THIS_DIR" )"
16 | REPO_ROOT="$( dirname "$THIS_DIR" )"
17 |
18 | MANIFEST_PATH="$REPO_ROOT/rust-uniffi/Cargo.toml"
19 | echo $MANIFEST_PATH
20 | if [[ ! -f "$MANIFEST_PATH" ]]; then
21 | echo "Could not locate Cargo.toml relative to script"
22 | exit 1
23 | fi
24 |
25 | LIB_NAME="libfeatureprobe_ffi.a"
26 |
27 | ####
28 | ##
29 | ## 1) Build the rust code individually for each target architecture.
30 | ##
31 | ####
32 |
33 | # Helper to run the cargo build command in a controlled environment.
34 | # It's important that we don't let environment variables from the user's default
35 | # desktop build environment leak into the iOS build, otherwise it might e.g.
36 | # link against the desktop build of NSS.
37 |
38 | CARGO="$HOME/.cargo/bin/cargo"
39 | LIBS_DIR="$REPO_ROOT/libs" # not work
40 |
41 | DEFAULT_RUSTFLAGS=""
42 | BUILD_ARGS=(+nightly build -Z build-std=std,panic_abort --manifest-path "$MANIFEST_PATH" --lib)
43 | case $BUILD_PROFILE in
44 | debug) ;;
45 | release)
46 | BUILD_ARGS=("${BUILD_ARGS[@]}" --release)
47 | # With debuginfo, the zipped artifact quickly baloons to many
48 | # hundred megabytes in size. Ideally we'd find a way to keep
49 | # the debug info but in a separate artifact.
50 | DEFAULT_RUSTFLAGS="-C debuginfo=0"
51 | ;;
52 | *) echo "Unknown build profile: $BUILD_PROFILE"; exit 1;
53 | esac
54 |
55 | echo $REPO_ROOT
56 |
57 | cargo_build () {
58 | TARGET=$1
59 | case $TARGET in
60 | x86_64*)
61 | LIBS_DIR="$REPO_ROOT/libs/ios/x86_64";;
62 | aarch64*)
63 | LIBS_DIR="$REPO_ROOT/libs/ios/arm64";;
64 | *)
65 | echo "Unexpected target architecture: $TARGET" && exit 1;;
66 | esac
67 | env -i \
68 | PATH="${PATH}" \
69 | RUSTC_WRAPPER="${RUSTC_WRAPPER:-}" \
70 | RUST_LOG="${RUST_LOG:-}" \
71 | RUSTFLAGS="${RUSTFLAGS:-$DEFAULT_RUSTFLAGS}" \
72 | "$CARGO" "${BUILD_ARGS[@]}" --target "$TARGET"
73 | }
74 |
75 | set -euvx
76 |
77 | # Intel iOS simulator
78 | CFLAGS_x86_64_apple_ios="-target x86_64-apple-ios" \
79 | cargo_build x86_64-apple-ios
80 |
81 | # Hardware iOS targets
82 | cargo_build aarch64-apple-ios
83 |
84 | # M1 iOS simulator.
85 | CFLAGS_aarch64_apple_ios_sim="--target aarch64-apple-ios-sim" \
86 | cargo_build aarch64-apple-ios-sim
87 |
88 | ####
89 | ##
90 | ## 2) Stitch the individual builds together an XCFramework bundle.
91 | ##
92 | ####
93 |
94 | TARGET_DIR="$REPO_ROOT/target"
95 | XCFRAMEWORK_ROOT="$THIS_DIR/$FRAMEWORK_NAME.xcframework"
96 |
97 | # Start from a clean slate.
98 |
99 | rm -rf "$XCFRAMEWORK_ROOT"
100 |
101 | # Build the directory structure right for an individual framework.
102 | # Most of this doesn't change between architectures.
103 |
104 | COMMON="$XCFRAMEWORK_ROOT/common/$FRAMEWORK_NAME.framework"
105 | PACKAGE_DIR="$THIS_DIR/client-sdk-ios"
106 |
107 | mkdir -p "$COMMON/Modules"
108 | cp "$THIS_DIR/module.modulemap" "$COMMON/Modules/"
109 | cp $THIS_DIR/ObjcFeatureProbe.swift $PACKAGE_DIR/Sources/FeatureProbe
110 | cp $THIS_DIR/LICENSE $PACKAGE_DIR/LICENSE
111 | cp $THIS_DIR/FeatureProbe.podspec $PACKAGE_DIR/FeatureProbe.podspec
112 | cp $THIS_DIR/Package.swift $PACKAGE_DIR/Package.swift
113 | cp $THIS_DIR/README.md $PACKAGE_DIR/README.md
114 |
115 | mkdir -p "$COMMON/Headers"
116 | # it would be neat if there was a single UniFFI command that would spit out
117 | # all of the generated headers for all UniFFIed dependencies of a given crate.
118 | # For now we generate the Swift bindings to get the headers as a side effect,
119 | # then delete the generated Swift code. Bleh.
120 | uniffi-bindgen generate "$REPO_ROOT/rust-uniffi/src/featureprobe.udl" -l swift -o "$COMMON/Headers"
121 | mv -f "$COMMON"/Headers/*.swift $PACKAGE_DIR/Sources/FeatureProbe
122 |
123 | # Flesh out the framework for each architecture based on the common files.
124 | # It's a little fiddly, because we apparently need to put all the simulator targets
125 | # together into a single fat binary, but keep the hardware target separate.
126 | # (TODO: we should try harder to see if we can avoid using `lipo` here, eliminating it
127 | # would make the overall system simpler to understand).
128 |
129 | # iOS hardware
130 | mkdir -p "$XCFRAMEWORK_ROOT/ios-arm64"
131 | cp -r "$COMMON" "$XCFRAMEWORK_ROOT/ios-arm64/$FRAMEWORK_NAME.framework"
132 | cp "$TARGET_DIR/aarch64-apple-ios/$BUILD_PROFILE/$LIB_NAME" "$XCFRAMEWORK_ROOT/ios-arm64/$FRAMEWORK_NAME.framework/$FRAMEWORK_NAME"
133 |
134 | # iOS simulator, with both platforms as a fat binary for mysterious reasons
135 | mkdir -p "$XCFRAMEWORK_ROOT/ios-arm64_x86_64-simulator"
136 | cp -r "$COMMON" "$XCFRAMEWORK_ROOT/ios-arm64_x86_64-simulator/$FRAMEWORK_NAME.framework"
137 | lipo -create \
138 | -output "$XCFRAMEWORK_ROOT/ios-arm64_x86_64-simulator/$FRAMEWORK_NAME.framework/$FRAMEWORK_NAME" \
139 | "$TARGET_DIR/aarch64-apple-ios-sim/$BUILD_PROFILE/$LIB_NAME" \
140 | "$TARGET_DIR/x86_64-apple-ios/$BUILD_PROFILE/$LIB_NAME"
141 |
142 | # Set up the metadata for the XCFramework as a whole.
143 |
144 | cp "$THIS_DIR/Info.plist" "$XCFRAMEWORK_ROOT/Info.plist"
145 |
146 | rm -rf "$XCFRAMEWORK_ROOT/common"
147 |
148 | rm -rf "$PACKAGE_DIR/$FRAMEWORK_NAME.xcframework"
149 | mv -f "$XCFRAMEWORK_ROOT" "$PACKAGE_DIR"
150 |
--------------------------------------------------------------------------------
/sdk-ios/module.modulemap:
--------------------------------------------------------------------------------
1 | framework module FeatureProbeFFI {
2 | umbrella header "FeatureprobeFFI.h"
3 |
4 | export *
5 | module * { export * }
6 | }
7 |
--------------------------------------------------------------------------------