diff --git a/.github/workflows/query_stats.yml b/.github/workflows/query_stats.yml new file mode 100644 index 000000000..7a762983a --- /dev/null +++ b/.github/workflows/query_stats.yml @@ -0,0 +1,28 @@ +name: query_stats + +on: + push: + branches: [master] + pull_request: + paths: + - motoko/query_stats/** + - .github/workflows/query_stats.yml + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + motoko-query_stats: + runs-on: ubuntu-24.04 + container: ghcr.io/dfinity/icp-dev-env-motoko:0.3.2 + env: + ICP_CLI_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - name: Deploy and test + working-directory: motoko/query_stats + run: | + icp network start -d + icp deploy + make test diff --git a/motoko/query_stats/.devcontainer/devcontainer.json b/motoko/query_stats/.devcontainer/devcontainer.json deleted file mode 100644 index ebb0b8bcc..000000000 --- a/motoko/query_stats/.devcontainer/devcontainer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "ICP Dev Environment", - "image": "ghcr.io/dfinity/icp-dev-env-slim:22", - "forwardPorts": [4943, 5173], - "portsAttributes": { - "4943": { - "label": "dfx", - "onAutoForward": "ignore" - }, - "5173": { - "label": "vite", - "onAutoForward": "openBrowser" - } - }, - "customizations": { - "vscode": { - "extensions": ["dfinity-foundation.vscode-motoko"] - } - } -} diff --git a/motoko/query_stats/BUILD.md b/motoko/query_stats/BUILD.md deleted file mode 100644 index 24cfcb754..000000000 --- a/motoko/query_stats/BUILD.md +++ /dev/null @@ -1,113 +0,0 @@ -# Continue building locally - -Projects deployed through ICP Ninja are temporary; they will only be live for 20 minutes before they are removed. The command-line tool `dfx` can be used to continue building your ICP Ninja project locally and deploy it to the mainnet. - -To migrate your ICP Ninja project off of the web browser and develop it locally, follow these steps. - -### 1. Install developer tools. - -You can install the developer tools natively or use Dev Containers. - -#### Option 1: Natively install developer tools - -> Installing `dfx` natively is currently only supported on macOS and Linux systems. On Windows, it is recommended to use the Dev Containers option. - -1. Install `dfx` with the following command: - -``` - -sh -ci "$(curl -fsSL https://internetcomputer.org/install.sh)" - -``` - -> On Apple Silicon (e.g., Apple M1 chip), make sure you have Rosetta installed (`softwareupdate --install-rosetta`). - -2. [Install NodeJS](https://nodejs.org/en/download/package-manager). - -3. For Rust projects, you will also need to: - -- Install [Rust](https://doc.rust-lang.org/cargo/getting-started/installation.html#install-rust-and-cargo): `curl https://sh.rustup.rs -sSf | sh` - -- Install [candid-extractor](https://crates.io/crates/candid-extractor): `cargo install candid-extractor` - -4. For Motoko projects, you will also need to: - -- Install the Motoko package manager [Mops](https://docs.mops.one/quick-start#2-install-mops-cli): `npm i -g ic-mops` - -Lastly, navigate into your project's directory that you downloaded from ICP Ninja. - -#### Option 2: Dev Containers - -Continue building your projects locally by installing the [Dev Container extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) for VS Code and [Docker](https://docs.docker.com/engine/install/). - -Make sure Docker is running, then navigate into your project's directory that you downloaded from ICP Ninja and start the Dev Container by selecting `Dev-Containers: Reopen in Container` in VS Code's command palette (F1 or Ctrl/Cmd+Shift+P). - -> Note that local development ports (e.g. the ports used by `dfx` or `vite`) are forwarded from the Dev Container to your local machine. In the VS code terminal, use Ctrl/Cmd+Click on the displayed local URLs to open them in your browser. To view the current port mappings, click the "Ports" tab in the VS Code terminal window. - -### 2. Start the local development environment. - -``` -dfx start --background -``` - -### 3. Create a local developer identity. - -To manage your project's canisters, it is recommended that you create a local [developer identity](https://internetcomputer.org/docs/building-apps/getting-started/identities) rather than use the `dfx` default identity that is not stored securely. - -To create a new identity, run the commands: - -``` - -dfx identity new IDENTITY_NAME - -dfx identity use IDENTITY_NAME - -``` - -Replace `IDENTITY_NAME` with your preferred identity name. The first command `dfx start --background` starts the local `dfx` processes, then `dfx identity new` will create a new identity and return your identity's seed phase. Be sure to save this in a safe, secure location. - -The third command `dfx identity use` will tell `dfx` to use your new identity as the active identity. Any canister smart contracts created after running `dfx identity use` will be owned and controlled by the active identity. - -Your identity will have a principal ID associated with it. Principal IDs are used to identify different entities on ICP, such as users and canisters. - -[Learn more about ICP developer identities](https://internetcomputer.org/docs/building-apps/getting-started/identities). - -### 4. Deploy the project locally. - -Deploy your project to your local developer environment with: - -``` -npm install -dfx deploy - -``` - -Your project will be hosted on your local machine. The local canister URLs for your project will be shown in the terminal window as output of the `dfx deploy` command. You can open these URLs in your web browser to view the local instance of your project. - -### 5. Obtain cycles. - -To deploy your project to the mainnet for long-term public accessibility, first you will need [cycles](https://internetcomputer.org/docs/building-apps/getting-started/tokens-and-cycles). Cycles are used to pay for the resources your project uses on the mainnet, such as storage and compute. - -> This cost model is known as ICP's [reverse gas model](https://internetcomputer.org/docs/building-apps/essentials/gas-cost), where developers pay for their project's gas fees rather than users pay for their own gas fees. This model provides an enhanced end user experience since they do not need to hold tokens or sign transactions when using a dapp deployed on ICP. - -> Learn how much a project may cost by using the [pricing calculator](https://internetcomputer.org/docs/building-apps/essentials/cost-estimations-and-examples). - -Cycles can be obtained through [converting ICP tokens into cycles using `dfx`](https://internetcomputer.org/docs/building-apps/developer-tools/dfx/dfx-cycles#dfx-cycles-convert). - -### 6. Deploy to the mainnet. - -Once you have cycles, run the command: - -``` - -dfx deploy --network ic - -``` - -After your project has been deployed to the mainnet, it will continuously require cycles to pay for the resources it uses. You will need to [top up](https://internetcomputer.org/docs/building-apps/canister-management/topping-up) your project's canisters or set up automatic cycles management through a service such as [CycleOps](https://cycleops.dev/). - -> If your project's canisters run out of cycles, they will be removed from the network. - -## Additional examples - -Additional code examples and sample applications can be found in the [DFINITY examples repo](https://github.com/dfinity/examples). diff --git a/motoko/query_stats/Makefile b/motoko/query_stats/Makefile new file mode 100644 index 000000000..ca4fc7d16 --- /dev/null +++ b/motoko/query_stats/Makefile @@ -0,0 +1,20 @@ +.PHONY: test + +test: + @echo "=== Test 1/2: load() returns a non-zero timestamp ===" + @# Uses --query so this call is counted in query_stats (update calls are not tracked) + @result=$$(icp canister call --query backend load '()') && \ + echo "$$result" && \ + echo "$$result" | grep -qE '\([0-9][0-9_]* : int\)' && \ + echo "PASS" || (echo "FAIL" && exit 1) + + @echo "=== Test 2/2: get_current_query_stats_as_string() returns the four expected fields ===" + @# NOTE: query stats are aggregated with a 2-epoch delay (120+ blocks on local replica). + @# This run's calls won't appear yet — run make test a second time to see non-zero values. + @result=$$(icp canister call backend get_current_query_stats_as_string '()') && \ + echo "$$result" && \ + echo "$$result" | grep -q 'Number of calls' && \ + echo "$$result" | grep -q 'Number of instructions' && \ + echo "$$result" | grep -q 'Request payload bytes' && \ + echo "$$result" | grep -q 'Response payload bytes' && \ + echo "PASS" || (echo "FAIL" && exit 1) diff --git a/motoko/query_stats/README.md b/motoko/query_stats/README.md index be49523e2..f5f50adab 100644 --- a/motoko/query_stats/README.md +++ b/motoko/query_stats/README.md @@ -1,23 +1,38 @@ -# Query stats - -## Deploying from ICP Ninja - -[![](https://icp.ninja/assets/open.svg)](https://icp.ninja/editor?g=https://github.com/dfinity/examples/tree/master/motoko/query_stats) - -## Build and deploy from the command-line - -### 1. [Download and install the IC SDK.](https://internetcomputer.org/docs/building-apps/getting-started/install) - -### 2. Download your project from ICP Ninja using the 'Download files' button on the upper left corner, or [clone the GitHub examples repository.](https://github.com/dfinity/examples/) - -### 3. Navigate into the project's directory. - -### 4. Deploy the project to your local environment: - -``` -dfx start --background --clean && dfx deploy -``` - -## Security considerations and best practices - -If you base your application on this example, it is recommended that you familiarize yourself with and adhere to the [security best practices](https://internetcomputer.org/docs/building-apps/security/overview) for developing on ICP. This example may not implement all the best practices. +# Query Stats + +This example demonstrates how a canister can read its own query statistics using `ic.canister_status`. It retrieves metrics such as the total number of query calls, instructions executed, and payload bytes. + +## How query stats work + +Query stats are **aggregated with a 2-epoch delay**, not updated per-call: + +- Each epoch is **60 blocks** on local PocketIC (vs 600 on mainnet) +- Stats for epoch N are only committed once 2/3+ of nodes have submitted records for epoch N+1 +- At least **2 epochs** (120+ blocks) must pass after a query call before it appears in `canister_status().query_stats` + +**On a local replica**, the first `make test` run will show `0` for all fields because the stats from that run haven't aggregated yet. Run `make test` a second time (with the same network still running) and you'll see non-zero values from the first run. + +## Build and deploy from the command line + +### Prerequisites +- Node.js +- icp-cli: `npm install -g @icp-sdk/icp-cli @icp-sdk/ic-wasm` + +### Install +```bash +git clone https://github.com/dfinity/examples +cd examples/motoko/query_stats +``` + +### Deploy and test +```bash +icp network start -d +icp deploy +make test # first run: stats show 0 (aggregation lag) +make test # second run: stats show non-zero values from the first run +icp network stop +``` + +## Security considerations and best practices + +Refer to the [security best practices](https://docs.internetcomputer.org/guides/security/overview) for information on security and best practices for your ICP app. diff --git a/motoko/query_stats/src/query_stats_backend/main.mo b/motoko/query_stats/backend/app.mo similarity index 64% rename from motoko/query_stats/src/query_stats_backend/main.mo rename to motoko/query_stats/backend/app.mo index 33fd7fb4a..ef0326cc1 100644 --- a/motoko/query_stats/src/query_stats_backend/main.mo +++ b/motoko/query_stats/backend/app.mo @@ -1,26 +1,16 @@ import Nat "mo:core/Nat"; -import Time "mo:core/Time"; import Principal "mo:core/Principal"; +import Time "mo:core/Time"; +import { ic } "mo:ic"; persistent actor QueryStats { - transient let IC = actor "aaaaa-aa" : actor { - canister_status : { canister_id : Principal } -> async { - query_stats : { - num_calls_total : Nat; - num_instructions_total : Nat; - request_payload_bytes_total : Nat; - response_payload_bytes_total : Nat; - }; - }; - }; - public query func load() : async Int { Time.now(); }; public func get_current_query_stats_as_string() : async Text { - let stats = await IC.canister_status({ + let stats = await ic.canister_status({ canister_id = Principal.fromActor(QueryStats); }); "Number of calls: " # stats.query_stats.num_calls_total.toText() # " - Number of instructions: " # stats.query_stats.num_instructions_total.toText() # " - Request payload bytes: " # stats.query_stats.request_payload_bytes_total.toText() # " - Response payload bytes: " # stats.query_stats.response_payload_bytes_total.toText(); diff --git a/motoko/query_stats/dfx.json b/motoko/query_stats/dfx.json deleted file mode 100644 index 3fff3f5cf..000000000 --- a/motoko/query_stats/dfx.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "canisters": { - "query_stats": { - "main": "src/query_stats_backend/main.mo", - "type": "motoko" - } - }, - "defaults": { - "build": { - "args": "", - "packtool": "mops sources" - } - }, - "output_env_file": ".env", - "version": 1 -} \ No newline at end of file diff --git a/motoko/query_stats/icp.yaml b/motoko/query_stats/icp.yaml new file mode 100644 index 000000000..fb741fade --- /dev/null +++ b/motoko/query_stats/icp.yaml @@ -0,0 +1,4 @@ +canisters: + - name: backend + recipe: + type: "@dfinity/motoko@v5.0.0" diff --git a/motoko/query_stats/mops.toml b/motoko/query_stats/mops.toml index 402697fa4..7902c42eb 100644 --- a/motoko/query_stats/mops.toml +++ b/motoko/query_stats/mops.toml @@ -1,14 +1,15 @@ -# Motoko dependencies (https://mops.one/) - [toolchain] -moc = "1.5.1" +moc = "1.9.0" [dependencies] -core = "2.4.0" - +core = "2.5.0" +ic = "4.0.0" [moc] -# M0236: use context dot notation (e.g. x.toText() instead of Nat.toText(x)) -# M0237: redundant explicit implicit arguments (e.g. Nat.compare is inferred automatically) -# M0223: redundant type instantiation (e.g. Array.tabulate instead of Array.tabulate) -args = ["-W=M0236,M0237,M0223"] +# M0236: use context dot notation +# M0237: redundant explicit implicit arguments +# M0223: redundant type instantiation +args = ["--default-persistent-actors", "-W=M0236,M0237,M0223"] + +[canisters.backend] +main = "backend/app.mo"