Skip to content

feat: add Invokable scripts API #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
Apr 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ jobs:
- restore_cache:
name: Restoring Example Cache
keys:
- &cache-example-key example-cache-v3-{{ checksum "Examples/CreateNewBucket/Package.swift" }}-{{ checksum "Examples/WriteData/Package.swift" }}-{{ checksum "Examples/QueryCpu/Package.swift" }}-{{ checksum "Examples/DeleteData/Package.swift" }}
- &cache-example-key example-cache-v3-{{ checksum "Examples/CreateNewBucket/Package.swift" }}-{{ checksum "Examples/WriteData/Package.swift" }}-{{ checksum "Examples/QueryCpu/Package.swift" }}-{{ checksum "Examples/DeleteData/Package.swift" }
- example-cache-v3-
- check-example:
directory: CreateNewBucket
Expand Down
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,5 @@ SourceKitten/
junit.xml
tests.xml

Scripts/cloud.yml
Scripts/oss.yml
Scripts/*.yml
Scripts/influxdb-clients-apigen/
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Features
1. [#49](https://github.com/influxdata/influxdb-client-swift/pull/49): Add support `async/await` functions
1. [#48](https://github.com/influxdata/influxdb-client-swift/pull/48): Add `InvokableScriptsApi` to create, update, list, delete and invoke scripts by seamless way

### API
1. [#49](https://github.com/influxdata/influxdb-client-swift/pull/49): Update InfluxDB API to latest version [OpenAPI]
Expand Down
2 changes: 1 addition & 1 deletion Examples/CreateNewBucket/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "CreateNewBucket", dependencies: [
Expand Down
2 changes: 1 addition & 1 deletion Examples/DeleteData/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "DeleteData", dependencies: [
Expand Down
2 changes: 1 addition & 1 deletion Examples/InfluxDBStatus/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "InfluxDBStatus", dependencies: [
Expand Down
36 changes: 36 additions & 0 deletions Examples/InvokableScripts/.swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
opt_in_rules:
- array_init
- collection_alignment
- contains_over_first_not_nil
- closure_end_indentation
- closure_spacing
- conditional_returns_on_newline
- empty_count
- empty_string
- explicit_init
- explicit_self
- fatal_error_message
- first_where
- implicit_return
- missing_docs
- modifier_order
- multiline_arguments
- multiline_literal_brackets
- multiline_parameters
- operator_usage_whitespace
- pattern_matching_keywords
- redundant_nil_coalescing
- redundant_type_annotation
- sorted_first_last
- sorted_imports
- trailing_closure
- unneeded_parentheses_in_closure_argument
- unused_import
- unused_declaration
- vertical_parameter_alignment_on_call
- vertical_whitespace_closing_braces
- vertical_whitespace_opening_braces

excluded:
- Package.swift
- .build/
23 changes: 23 additions & 0 deletions Examples/InvokableScripts/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// swift-tools-version:5.5

import PackageDescription

let package = Package(
name: "InvokableScripts",
platforms: [
.macOS(.v10_15)
],
products: [
.executable(name: "invokable-scripts", targets: ["InvokableScripts"])
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.1.2")
],
targets: [
.executableTarget(name: "InvokableScripts", dependencies: [
.product(name: "InfluxDBSwift", package: "influxdb-client-swift"),
.product(name: "ArgumentParser", package: "swift-argument-parser")
])
]
)
100 changes: 100 additions & 0 deletions Examples/InvokableScripts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# InvokableScripts

This is an example how to use Invokable scripts Cloud API to create custom endpoints that query data.
> :warning: Invokable Scripts are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.

## Prerequisites:
- Docker
- Cloned examples:
```bash
git clone git@github.com:influxdata/influxdb-client-swift.git
cd Examples/InvokableScripts
```

## Sources:
- [Package.swift](/Examples/InvokableScripts/Package.swift)
- [InvokableScripts.swift](/Examples/InvokableScripts/Sources/InvokableScripts/InvokableScripts.swift)

## How to test:
1. Start SwiftCLI by:
```bash
docker run --rm \
--privileged \
--interactive \
--tty \
--volume $PWD/../..:/client \
--workdir /client/Examples/InvokableScripts \
swift:5.6 /bin/bash
```
1. Run Example by:
```bash
swift run invokable-scripts --org my-org --bucket my-bucket --token my-token --url https://us-west-2-1.aws.cloud2.influxdata.com
```

## Expected output

```bash
------- Create -------

▿ InfluxDBSwift.Script
▿ id: Optional("0945186f3962f000")
- some: "0945186f3962f000"
- name: "my_script_1650951739.551672"
▿ description: Optional("my first try")
- some: "my first try"
- orgID: "04014de4ed590000"
- script: "from(bucket: params.bucket_name) |> range(start: -30d) |> limit(n:2)"
▿ language: Optional(InfluxDBSwift.ScriptLanguage.flux)
- some: InfluxDBSwift.ScriptLanguage.flux
- url: nil
▿ createdAt: Optional(2022-04-26 05:42:19 +0000)
▿ some: 2022-04-26 05:42:19 +0000
- timeIntervalSinceReferenceDate: 672644539.621
▿ updatedAt: Optional(2022-04-26 05:42:19 +0000)
▿ some: 2022-04-26 05:42:19 +0000
- timeIntervalSinceReferenceDate: 672644539.621

------- Update -------

▿ InfluxDBSwift.Script
▿ id: Optional("0945186f3962f000")
- some: "0945186f3962f000"
- name: "my_script_1650951739.551672"
▿ description: Optional("my updated description")
- some: "my updated description"
- orgID: "04014de4ed590000"
- script: "from(bucket: params.bucket_name) |> range(start: -30d) |> limit(n:2)"
▿ language: Optional(InfluxDBSwift.ScriptLanguage.flux)
- some: InfluxDBSwift.ScriptLanguage.flux
- url: nil
▿ createdAt: Optional(2022-04-26 05:42:19 +0000)
▿ some: 2022-04-26 05:42:19 +0000
- timeIntervalSinceReferenceDate: 672644539.621
▿ updatedAt: Optional(2022-04-26 05:42:19 +0000)
▿ some: 2022-04-26 05:42:19 +0000
- timeIntervalSinceReferenceDate: 672644539.8399999

------- List -------

Scripts:
0945186f3962f000: my_script_1650951739.551672: my updated description

------- Invoke to FluxRecords -------

Prague: 25.3
New York: 24.3

------- Invoke to Raw -------

RAW output:

,result,table,_start,_stop,_time,_value,_field,_measurement,location
,_result,1,2022-03-27T05:42:20.589649766Z,2022-04-26T05:42:20.589649766Z,2022-03-28T07:59:52Z,25.3,temperature,my_measurement,Prague
,_result,2,2022-03-27T05:42:20.589649766Z,2022-04-26T05:42:20.589649766Z,2022-03-28T07:59:52Z,24.3,temperature,my_measurement,New York


------- Delete -------

Successfully deleted script: 'my_script_1650951739.551672'

```
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
//
// Warning: Invokable Scripts are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.
//

import ArgumentParser
import Foundation
import InfluxDBSwift

@main
struct InvokableScriptsAPI: AsyncParsableCommand {
@Option(name: .shortAndLong, help: "The bucket to query. The name or id of the bucket destination.")
private var bucket: String

@Option(name: .shortAndLong,
help: "The organization executing the query. Takes either the `ID` or `Name` interchangeably.")
private var org: String

@Option(name: .shortAndLong, help: "Authentication token.")
private var token: String

@Option(name: .shortAndLong, help: "HTTP address of InfluxDB Cloud.")
private var url: String
}

extension InvokableScriptsAPI {
mutating func run() async throws {
//
// Initialize Client with default Organization
//
let client = InfluxDBClient(
url: url,
token: token,
options: InfluxDBClient.InfluxDBOptions(bucket: self.bucket, org: self.org))

let invokableScriptsApi = client.invokableScriptsApi

//
// Prepare Data
//
let point1 = InfluxDBClient
.Point("my_measurement")
.addTag(key: "location", value: "Prague")
.addField(key: "temperature", value: .double(25.3))
let point2 = InfluxDBClient
.Point("my_measurement")
.addTag(key: "location", value: "New York")
.addField(key: "temperature", value: .double(24.3))
try await client.makeWriteAPI().write(points: [point1, point2])

//
// Create Invokable Script
//
print("------- Create -------\n")
let scriptQuery = "from(bucket: params.bucket_name) |> range(start: -30d) |> limit(n:2)"
let createRequest = ScriptCreateRequest(
name: "my_script_\(Date().timeIntervalSince1970)",
description: "my first try",
script: scriptQuery,
language: ScriptLanguage.flux)

let createdScript = try await invokableScriptsApi.createScript(createRequest: createRequest)
guard let createdScript = createdScript else {
return
}
dump(createdScript)

//
// Update Invokable Script
//
print("\n------- Update -------\n")
let updateRequest = ScriptUpdateRequest(description: "my updated description")
let updatedScript = try await invokableScriptsApi.updateScript(scriptId: createdScript.id!, updateRequest: updateRequest)
guard let updatedScript = updatedScript else {
return
}
dump(updatedScript)

//
// List Invokable Scripts
//
print("\n------- List -------\n")
let scripts = try await invokableScriptsApi.findScripts()
print("Scripts:")
scripts?.scripts?.forEach { print("\t\($0.id ?? ""): \($0.name): \($0.description ?? "")") }

//
// Invoke a Script
//
// FluxRecords
print("\n------- Invoke to FluxRecords -------\n")
let records = try await invokableScriptsApi.invokeScript(
scriptId: updatedScript.id!,
params: ["bucket_name": "\(self.bucket)"])
try records.forEach { record in
print("\t\(record.values["location"]!): \(record.values["_value"]!)")
}
// Raw
print("\n------- Invoke to Raw -------\n")
let raw = try await invokableScriptsApi.invokeScriptRaw(
scriptId: updatedScript.id!,
params: ["bucket_name": "\(self.bucket)"])
print("RAW output:\n\n \(String(decoding: raw, as: UTF8.self))")

//
// Delete previously created Script
//
print("\n------- Delete -------\n")
try await invokableScriptsApi.deleteScript(scriptId: updatedScript.id!)
print("Successfully deleted script: '\(updatedScript.name)'")

client.close()
}
}
2 changes: 1 addition & 1 deletion Examples/ParameterizedQuery/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "ParameterizedQuery", dependencies: [
Expand Down
2 changes: 1 addition & 1 deletion Examples/QueryCpu/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "QueryCpu", dependencies: [
Expand Down
1 change: 1 addition & 0 deletions Examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@
- [DeleteData](DeleteData#deletedata) - How to delete data with specified predicate
- [AsyncAwait](AsyncAwait#asyncawait) - How to use `async/await` with the InfluxDB client.
- [InfluxDBStatus](InfluxDBStatus#influxdbstatus) - This is an example how to check status of InfluxDB
- [InvokableScripts](InvokableScripts#invokablescripts) - How to use Invokable scripts Cloud API to create custom endpoints that query data

2 changes: 1 addition & 1 deletion Examples/WriteData/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "WriteData", dependencies: [
Expand Down
2 changes: 1 addition & 1 deletion Examples/WriteDataInBatches/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ let package = Package(
],
dependencies: [
.package(name: "influxdb-client-swift", path: "../../"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0")
],
targets: [
.target(name: "WriteDataInBatches", dependencies: [
Expand Down
Loading