Skip to content

Commit d831745

Browse files
committed
Introduce ENV simulation
1 parent f28eae6 commit d831745

File tree

13 files changed

+251
-69
lines changed

13 files changed

+251
-69
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@ xcuserdata
99
Package.resolved
1010
.serverless
1111
docker
12-
.env
12+
.env

README.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ public protocol ByteBufferSCFHandler {
158158
/// The SCF handling method.
159159
/// Concrete SCF handlers implement this method to provide the SCF functionality.
160160
///
161-
/// - parameters:
161+
/// - Parameters:
162162
/// - context: Runtime `Context`.
163163
/// - event: The event or input payload encoded as `ByteBuffer`.
164164
///
@@ -191,7 +191,7 @@ public protocol EventLoopSCFHandler: ByteBufferSCFHandler {
191191
/// The SCF handling method.
192192
/// Concrete SCF handlers implement this method to provide the SCF functionality.
193193
///
194-
/// - parameters:
194+
/// - Parameters:
195195
/// - context: Runtime `Context`.
196196
/// - event: Event of type `In` representing the event or request.
197197
///
@@ -201,7 +201,8 @@ public protocol EventLoopSCFHandler: ByteBufferSCFHandler {
201201

202202
/// Encode a response of type `Out` to `ByteBuffer`.
203203
/// Concrete SCF handlers implement this method to provide coding functionality.
204-
/// - parameters:
204+
///
205+
/// - Parameters:
205206
/// - allocator: A `ByteBufferAllocator` to help allocate the `ByteBuffer`.
206207
/// - value: Response of type `Out`.
207208
///
@@ -211,7 +212,7 @@ public protocol EventLoopSCFHandler: ByteBufferSCFHandler {
211212
/// Decode a`ByteBuffer` to a request or event of type `In`
212213
/// Concrete SCF handlers implement this method to provide coding functionality.
213214
///
214-
/// - parameters:
215+
/// - Parameters:
215216
/// - buffer: The `ByteBuffer` to decode.
216217
///
217218
/// - Returns: A request or event of type `In`.
@@ -235,7 +236,7 @@ public protocol SCFHandler: EventLoopSCFHandler {
235236
/// The SCF handling method.
236237
/// Concrete SCF handlers implement this method to provide the SCF functionality.
237238
///
238-
/// - parameters:
239+
/// - Parameters:
239240
/// - context: Runtime `Context`.
240241
/// - event: Event of type `In` representing the event or request.
241242
/// - callback: Completion handler to report the result of the SCF function back to the runtime engine.
@@ -298,13 +299,13 @@ public final class Context: CustomDebugStringConvertible {
298299

299300
/// `Logger` to log with.
300301
///
301-
/// - note: The `LogLevel` can be configured using the `LOG_LEVEL` environment variable.
302+
/// - Note: The `LogLevel` can be configured using the `LOG_LEVEL` environment variable.
302303
public let logger: Logger
303304

304305
/// The `EventLoop` the SCF function is executed on. Use this to schedule work with.
305306
/// This is useful when implementing the `EventLoopSCFHandler` protocol.
306307
///
307-
/// - note: The `EventLoop` is shared with the SCF Runtime Engine and should be handled with extra care.
308+
/// - Note: The `EventLoop` is shared with the SCF Runtime Engine and should be handled with extra care.
308309
/// Most importantly the `EventLoop` must never be blocked.
309310
public let eventLoop: EventLoop
310311

Sources/TencentSCFRuntime/SCF+Codable.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ extension SCF {
3838

3939
/// Run a cloud function defined by implementing the `CodableClosure` function.
4040
///
41-
/// - parameters:
41+
/// - Parameters:
4242
/// - closure: `CodableClosure` based SCF function.
4343
///
44-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
44+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
4545
public static func run<In: Decodable, Out: Encodable>(_ closure: @escaping CodableClosure<In, Out>) {
4646
self.run(CodableClosureWrapper(closure))
4747
}
@@ -51,10 +51,10 @@ extension SCF {
5151

5252
/// Run a cloud function defined by implementing the `CodableVoidClosure` function.
5353
///
54-
/// - parameters:
54+
/// - Parameters:
5555
/// - closure: `CodableVoidClosure` based SCF function.
5656
///
57-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
57+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
5858
public static func run<In: Decodable>(_ closure: @escaping CodableVoidClosure<In>) {
5959
self.run(CodableVoidClosureWrapper(closure))
6060
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//===------------------------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftTencentSCFRuntime open source project
4+
//
5+
// Copyright (c) 2020 stevapple and the SwiftTencentSCFRuntime project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftTencentSCFRuntime project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===------------------------------------------------------------------------------------===//
14+
15+
#if os(Linux)
16+
import Glibc
17+
#else
18+
import Darwin.C
19+
#endif
20+
21+
// MARK: Env
22+
23+
extension SCF {
24+
/// Environment variables helper for SCF.
25+
public enum Env {
26+
#if DEBUG
27+
/// Preset overriding to simulate the SCF runtime context.
28+
private static let preset = [
29+
"TENCENTCLOUD_UIN": "100000000001",
30+
"TENCENTCLOUD_APPID": "1250000000",
31+
"TENCENTCLOUD_REGION": "ap-beijing",
32+
"SCF_FUNCTIONNAME": "my-swift-function",
33+
"SCF_NAMESPACE": "default",
34+
"SCF_FUNCTIONVERSION": "$LATEST",
35+
]
36+
37+
/// Custom environment variables overriding.
38+
private static var custom: [String: String] = [:]
39+
40+
/// Batch override environment variables with `Dictionary`.
41+
public static func update(with dictionary: [String: String]) {
42+
Self.custom.merge(dictionary) { $1 }
43+
}
44+
45+
/// Utility to read/override environment variables.
46+
public static subscript(_ key: String) -> String? {
47+
get {
48+
if let value = Self.custom[key] {
49+
return value
50+
} else if let value = getenv(key) {
51+
return String(cString: value)
52+
} else if let value = Self.preset[key] {
53+
return value
54+
} else {
55+
return nil
56+
}
57+
}
58+
set(newValue) {
59+
Self.custom[key] = newValue
60+
}
61+
}
62+
63+
// for testing and internal use
64+
internal static func reset() {
65+
Self.custom = [:]
66+
}
67+
#else
68+
/// Utility to read environment variables.
69+
public static subscript(_ key: String) -> String? {
70+
guard let value = getenv(key) else {
71+
return nil
72+
}
73+
return String(cString: value)
74+
}
75+
#endif
76+
}
77+
}

Sources/TencentSCFRuntimeCore/SCF+LocalServer.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,11 @@ import NIOHTTP1
4444
extension SCF {
4545
/// Execute code in the context of a mock SCF server.
4646
///
47-
/// - parameters:
47+
/// - Parameters:
4848
/// - invocationEndpoint: The endpoint to post events to.
4949
/// - body: Code to run within the context of the mock server. Typically this would be a `SCF.run` function call.
5050
///
51-
/// - note: This API is designed stricly for local testing and is behind a DEBUG flag.
51+
/// - Note: This API is designed stricly for local testing and is behind a DEBUG flag.
5252
@discardableResult
5353
static func withLocalServer<Value>(invocationEndpoint: String? = nil, _ body: @escaping () -> Value) throws -> Value {
5454
let server = LocalFunction.Server(invocationEndpoint: invocationEndpoint)

Sources/TencentSCFRuntimeCore/SCF+String.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ extension SCF {
3434

3535
/// Run a cloud function defined by implementing the `StringClosure` function.
3636
///
37-
/// - parameters:
37+
/// - Parameters:
3838
/// - closure: `StringClosure` based SCF function.
3939
///
40-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
40+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
4141
public static func run(_ closure: @escaping StringClosure) {
4242
self.run(closure: closure)
4343
}
@@ -47,10 +47,10 @@ extension SCF {
4747

4848
/// Run a cloud function defined by implementing the `StringVoidClosure` function.
4949
///
50-
/// - parameters:
50+
/// - Parameters:
5151
/// - closure: `StringVoidClosure` based SCF function.
5252
///
53-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
53+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
5454
public static func run(_ closure: @escaping StringVoidClosure) {
5555
self.run(closure: closure)
5656
}

Sources/TencentSCFRuntimeCore/SCF.swift

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,6 @@
2525
//
2626
//===------------------------------------------------------------------------------------===//
2727

28-
#if os(Linux)
29-
import Glibc
30-
#else
31-
import Darwin.C
32-
#endif
33-
3428
import Backtrace
3529
import Logging
3630
import NIO
@@ -44,10 +38,10 @@ public enum SCF {
4438

4539
/// Run a cloud function defined by implementing the `SCFHandler` protocol.
4640
///
47-
/// - parameters:
41+
/// - Parameters:
4842
/// - handler: `ByteBufferSCFHandler` based SCF function.
4943
///
50-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
44+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
5145
public static func run(_ handler: Handler) {
5246
self.run(handler: handler)
5347
}
@@ -56,32 +50,24 @@ public enum SCF {
5650
/// Use this to initialize all your resources that you want to cache between invocations. This could be database connections and HTTP clients for example.
5751
/// It is encouraged to use the given `EventLoop`'s conformance to `EventLoopGroup` when initializing NIO dependencies. This will improve overall performance.
5852
///
59-
/// - parameters:
53+
/// - Parameters:
6054
/// - factory: A `ByteBufferSCFHandler` factory.
6155
///
62-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
56+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
6357
public static func run(_ factory: @escaping HandlerFactory) {
6458
self.run(factory: factory)
6559
}
6660

6761
/// Run a cloud function defined by implementing the `SCFHandler` protocol provided via a factory, typically a constructor.
6862
///
69-
/// - parameters:
63+
/// - Parameters:
7064
/// - factory: A `ByteBufferSCFHandler` factory.
7165
///
72-
/// - note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
66+
/// - Note: This is a blocking operation that will run forever, as its lifecycle is managed by the Tencent SCF Runtime Engine.
7367
public static func run(_ factory: @escaping (InitializationContext) throws -> Handler) {
7468
self.run(factory: factory)
7569
}
7670

77-
/// Utility to access/read environment variables.
78-
public static func env(_ name: String) -> String? {
79-
guard let value = getenv(name) else {
80-
return nil
81-
}
82-
return String(cString: value)
83-
}
84-
8571
// for testing and internal use
8672
@discardableResult
8773
internal static func run(configuration: Configuration = .init(), handler: Handler) -> Result<Int, Error> {
@@ -145,7 +131,7 @@ public enum SCF {
145131

146132
// Start local server for debugging in DEBUG mode only.
147133
#if DEBUG
148-
if SCF.env("LOCAL_SCF_SERVER_ENABLED").flatMap(Bool.init) ?? false {
134+
if SCF.Env["LOCAL_SCF_SERVER_ENABLED"].flatMap(Bool.init) ?? false {
149135
do {
150136
return try SCF.withLocalServer {
151137
_run(configuration, factory)

Sources/TencentSCFRuntimeCore/SCFConfiguration.swift

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ extension SCF {
4949
let logLevel: Logger.Level
5050

5151
init(logLevel: Logger.Level? = nil) {
52-
self.logLevel = logLevel ?? env("LOG_LEVEL").flatMap(Logger.Level.init) ?? .info
52+
self.logLevel = logLevel ?? Env["LOG_LEVEL"].flatMap(Logger.Level.init) ?? .info
5353
}
5454

5555
var description: String {
@@ -64,8 +64,8 @@ extension SCF {
6464

6565
init(id: String? = nil, maxTimes: Int? = nil, stopSignal: Signal? = nil) {
6666
self.id = id ?? "\(DispatchTime.now().uptimeNanoseconds)"
67-
self.maxTimes = maxTimes ?? env("MAX_REQUESTS").flatMap(Int.init) ?? 0
68-
self.stopSignal = stopSignal ?? env("STOP_SIGNAL").flatMap(Int32.init).flatMap(Signal.init) ?? Signal.TERM
67+
self.maxTimes = maxTimes ?? Env["MAX_REQUESTS"].flatMap(Int.init) ?? 0
68+
self.stopSignal = stopSignal ?? Env["STOP_SIGNAL"].flatMap(Int32.init).flatMap(Signal.init) ?? Signal.TERM
6969
precondition(self.maxTimes >= 0, "maxTimes must be equal or larger than 0")
7070
}
7171

@@ -88,11 +88,11 @@ extension SCF {
8888
self.ip = String(ipPort[0])
8989
self.port = port
9090
} else {
91-
self.ip = env("SCF_RUNTIME_API") ?? "127.0.0.1"
92-
self.port = env("SCF_RUNTIME_API_PORT").flatMap(Int.init) ?? 9001
91+
self.ip = Env["SCF_RUNTIME_API"] ?? "127.0.0.1"
92+
self.port = Env["SCF_RUNTIME_API_PORT"].flatMap(Int.init) ?? 9001
9393
}
94-
self.keepAlive = keepAlive ?? env("KEEP_ALIVE").flatMap(Bool.init) ?? true
95-
self.requestTimeout = requestTimeout ?? env("REQUEST_TIMEOUT").flatMap(Int64.init).flatMap { .milliseconds($0) }
94+
self.keepAlive = keepAlive ?? Env["KEEP_ALIVE"].flatMap(Bool.init) ?? true
95+
self.requestTimeout = requestTimeout ?? Env["REQUEST_TIMEOUT"].flatMap(Int64.init).flatMap { .milliseconds($0) }
9696
}
9797

9898
var description: String {

0 commit comments

Comments
 (0)