Initial Commit

This commit is contained in:
Christian Risi 2024-12-08 20:38:43 +00:00
parent c2539d2250
commit c863c66236
9 changed files with 335 additions and 287 deletions

View File

@ -1,32 +1,43 @@
{ {
// Displayed name // Displayed name
"name": "IoT-Simulator", "name": "IoT-Simulator",
// Image to be used // Image to be used
"image": "swift", "image": "swift",
// Env in container // Env in container
"containerEnv": { "containerEnv": {
}, },
// Mounts in container // Customization
"mounts": [ "customizations": {
{ "vscode": {
"source": "${localWorkspaceFolder}", "extensions": [
"target": "/workspace", "sswg.swift-lang",
"type": "bind" "fabiospampinato.vscode-highlight",
} "fabiospampinato.vscode-todo-plus"
], ]
}
// The WorkspaceFolder inside container },
"workspaceFolder": "/workspace",
// Mounts in container
// RunArgs "mounts": [
"runArgs": [ {
"--name", "source": "${localWorkspaceFolder}",
"IoT-Simulator-Vapor" "target": "/workspace",
] "type": "bind"
}
],
// The WorkspaceFolder inside container
"workspaceFolder": "/workspace",
// RunArgs
"runArgs": [
"--name",
"IoT-Simulator-Vapor"
]
} }

230
.gitignore vendored
View File

@ -1,116 +1,116 @@
############################## ##############################
## macOS ## macOS
############################## ##############################
# General # General
.DS_Store .DS_Store
.AppleDouble .AppleDouble
.LSOverride .LSOverride
# Icon must end with two \r # Icon must end with two \r
Icon Icon
# Thumbnails # Thumbnails
._* ._*
# Files that might appear in the root of a volume # Files that might appear in the root of a volume
.DocumentRevisions-V100 .DocumentRevisions-V100
.fseventsd .fseventsd
.Spotlight-V100 .Spotlight-V100
.TemporaryItems .TemporaryItems
.Trashes .Trashes
.VolumeIcon.icns .VolumeIcon.icns
.com.apple.timemachine.donotpresent .com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share # Directories potentially created on remote AFP share
.AppleDB .AppleDB
.AppleDesktop .AppleDesktop
Network Trash Folder Network Trash Folder
Temporary Items Temporary Items
.apdisk .apdisk
############################## ##############################
## Swift ## Swift
############################## ##############################
# Xcode # Xcode
# #
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings ## User settings
xcuserdata/ xcuserdata/
## Obj-C/Swift specific ## Obj-C/Swift specific
*.hmap *.hmap
## App packaging ## App packaging
*.ipa *.ipa
*.dSYM.zip *.dSYM.zip
*.dSYM *.dSYM
## Playgrounds ## Playgrounds
timeline.xctimeline timeline.xctimeline
playground.xcworkspace playground.xcworkspace
# Swift Package Manager # Swift Package Manager
# #
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/ # Packages/
# Package.pins # Package.pins
# Package.resolved # Package.resolved
# *.xcodeproj # *.xcodeproj
# #
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project # hence it is not needed unless you have added a package configuration file to your project
# .swiftpm # .swiftpm
.build/ .build/
# CocoaPods # CocoaPods
# #
# We recommend against adding the Pods directory to your .gitignore. However # We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at: # you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
# #
# Pods/ # Pods/
# #
# Add this line if you want to avoid checking in source code from the Xcode workspace # Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace # *.xcworkspace
# Carthage # Carthage
# #
# Add this line if you want to avoid checking in source code from Carthage dependencies. # Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts # Carthage/Checkouts
Carthage/Build/ Carthage/Build/
# fastlane # fastlane
# #
# It is recommended to not store the screenshots in the git repo. # It is recommended to not store the screenshots in the git repo.
# Instead, use fastlane to re-generate the screenshots whenever they are needed. # Instead, use fastlane to re-generate the screenshots whenever they are needed.
# For more information about the recommended setup visit: # For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control # https://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml fastlane/report.xml
fastlane/Preview.html fastlane/Preview.html
fastlane/screenshots/**/*.png fastlane/screenshots/**/*.png
fastlane/test_output fastlane/test_output
############################## ##############################
## Vapor ## Vapor
############################## ##############################
Packages Packages
.build .build
.DS_Store .DS_Store
*.xcodeproj *.xcodeproj
DerivedData/ DerivedData/
Package.resolved Package.resolved
.swiftpm .swiftpm
Tests/LinuxMain.swift Tests/LinuxMain.swift
.bash_history .bash_history
.cache/ .cache/
# API Docs Generation # API Docs Generation
generate-package-api-docs.swift generate-package-api-docs.swift
theme-settings.json theme-settings.json

60
.vscode/launch.json vendored
View File

@ -1,22 +1,40 @@
{ {
"configurations": [ "configurations": [
{ {
"type": "lldb", "type": "lldb",
"request": "launch", "request": "launch",
"args": [], "args": [],
"cwd": "${workspaceFolder:workspace}", "cwd": "${workspaceFolder:workspace}",
"name": "Debug IoT-Simulator", "name": "Debug IoT-Simulator",
"program": "${workspaceFolder:workspace}/.build/debug/IoT-Simulator", "program": "${workspaceFolder:workspace}/.build/debug/IoT-Simulator",
"preLaunchTask": "swift: Build Debug IoT-Simulator" "preLaunchTask": "swift: Build Debug IoT-Simulator"
}, },
{ {
"type": "lldb", "type": "lldb",
"request": "launch", "request": "launch",
"args": [], "args": [],
"cwd": "${workspaceFolder:workspace}", "cwd": "${workspaceFolder:workspace}",
"name": "Release IoT-Simulator", "name": "Release IoT-Simulator",
"program": "${workspaceFolder:workspace}/.build/release/IoT-Simulator", "program": "${workspaceFolder:workspace}/.build/release/IoT-Simulator",
"preLaunchTask": "swift: Build Release IoT-Simulator" "preLaunchTask": "swift: Build Release IoT-Simulator"
} },
] {
"type": "lldb",
"request": "launch",
"args": [],
"cwd": "${workspaceFolder:workspace}",
"name": "Debug App",
"program": "${workspaceFolder:workspace}/.build/debug/App",
"preLaunchTask": "swift: Build Debug App"
},
{
"type": "lldb",
"request": "launch",
"args": [],
"cwd": "${workspaceFolder:workspace}",
"name": "Release App",
"program": "${workspaceFolder:workspace}/.build/release/App",
"preLaunchTask": "swift: Build Release App"
}
]
} }

View File

@ -1,40 +1,44 @@
// swift-tools-version:6.0 // swift-tools-version:6.0
import PackageDescription import PackageDescription
let package = Package( let package = Package(
name: "template-bare", name: "template-bare",
platforms: [ platforms: [
.macOS(.v13) .macOS(.v13)
], ],
dependencies: [ dependencies: [
// 💧 A server-side Swift web framework. // 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "4.99.3"), .package(url: "https://github.com/vapor/vapor.git", from: "4.99.3"),
// 🔵 Non-blocking, event-driven networking for Swift. Used for custom executors // 🔵 Non-blocking, event-driven networking for Swift. Used for custom executors
.package(url: "https://github.com/apple/swift-nio.git", from: "2.65.0"), .package(url: "https://github.com/apple/swift-nio.git", from: "2.65.0"),
], .package(url: "https://github.com/apple/swift-crypto.git", branch: "main"),
targets: [ .package(url: "https://repositories.communitynotfound.work/PoliBa-Software-Architecture/Swift-MessageUtils.git", branch: "main")
.executableTarget( ],
name: "App", targets: [
dependencies: [ .executableTarget(
.product(name: "Vapor", package: "vapor"), name: "App",
.product(name: "NIOCore", package: "swift-nio"), dependencies: [
.product(name: "NIOPosix", package: "swift-nio"), .product(name: "Vapor", package: "vapor"),
], .product(name: "NIOCore", package: "swift-nio"),
swiftSettings: swiftSettings .product(name: "NIOPosix", package: "swift-nio"),
), .product(name: "Crypto", package: "swift-crypto"),
.testTarget( .product(name: "MessageUtils", package: "Swift-MessageUtils"),
name: "AppTests", ],
dependencies: [ swiftSettings: swiftSettings
.target(name: "App"), ),
.product(name: "XCTVapor", package: "vapor"), .testTarget(
], name: "AppTests",
swiftSettings: swiftSettings dependencies: [
) .target(name: "App"),
], .product(name: "XCTVapor", package: "vapor"),
swiftLanguageModes: [.v5] ],
) swiftSettings: swiftSettings
)
var swiftSettings: [SwiftSetting] { [ ],
.enableUpcomingFeature("DisableOutwardActorInference"), swiftLanguageModes: [.v5]
.enableExperimentalFeature("StrictConcurrency"), )
] }
var swiftSettings: [SwiftSetting] { [
.enableUpcomingFeature("DisableOutwardActorInference"),
.enableExperimentalFeature("StrictConcurrency"),
] }

View File

@ -0,0 +1,13 @@
import Crypto
public func createPrivateP256Key() -> P256.Signing.PrivateKey {
return P256.Signing.PrivateKey()
}
public func createPublickP256Key(privateKey: P256.Signing.PrivateKey ) -> P256.Signing.PublicKey {
return privateKey.publicKey
}
public func publicP256_2_Spki(publicKey: P256.Signing.PublicKey) -> String {
return publicKey.pemRepresentation
}

View File

@ -1,9 +1,9 @@
import Vapor import Vapor
// configures your application // configures your application
public func configure(_ app: Application) async throws { public func configure(_ app: Application) async throws {
// uncomment to serve files from /Public folder // uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory)) // app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
// register routes // register routes
try routes(app) try routes(app)
} }

View File

@ -1,31 +1,31 @@
import Vapor import Vapor
import Logging import Logging
import NIOCore import NIOCore
import NIOPosix import NIOPosix
@main @main
enum Entrypoint { enum Entrypoint {
static func main() async throws { static func main() async throws {
var env = try Environment.detect() var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env) try LoggingSystem.bootstrap(from: &env)
let app = try await Application.make(env) let app = try await Application.make(env)
// This attempts to install NIO as the Swift Concurrency global executor. // This attempts to install NIO as the Swift Concurrency global executor.
// You can enable it if you'd like to reduce the amount of context switching between NIO and Swift Concurrency. // You can enable it if you'd like to reduce the amount of context switching between NIO and Swift Concurrency.
// Note: this has caused issues with some libraries that use `.wait()` and cleanly shutting down. // Note: this has caused issues with some libraries that use `.wait()` and cleanly shutting down.
// If enabled, you should be careful about calling async functions before this point as it can cause assertion failures. // If enabled, you should be careful about calling async functions before this point as it can cause assertion failures.
// let executorTakeoverSuccess = NIOSingletons.unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor() // let executorTakeoverSuccess = NIOSingletons.unsafeTryInstallSingletonPosixEventLoopGroupAsConcurrencyGlobalExecutor()
// app.logger.debug("Tried to install SwiftNIO's EventLoopGroup as Swift's global concurrency executor", metadata: ["success": .stringConvertible(executorTakeoverSuccess)]) // app.logger.debug("Tried to install SwiftNIO's EventLoopGroup as Swift's global concurrency executor", metadata: ["success": .stringConvertible(executorTakeoverSuccess)])
do { do {
try await configure(app) try await configure(app)
} catch { } catch {
app.logger.report(error: error) app.logger.report(error: error)
try? await app.asyncShutdown() try? await app.asyncShutdown()
throw error throw error
} }
try await app.execute() try await app.execute()
try await app.asyncShutdown() try await app.asyncShutdown()
} }
} }

View File

@ -1,11 +1,13 @@
import Vapor import Vapor
import MessageUtils
func routes(_ app: Application) throws { import Foundation
app.get { req async in
"It works!" func routes(_ app: Application) throws {
} app.get { req async in
"It works!"
app.get("hello") { req async -> String in }
"Hello, world!"
} app.get("hello") { req async -> String in
} return "Hello, world!"
}
}

View File

@ -1,29 +1,29 @@
@testable import App @testable import App
import XCTVapor import XCTVapor
import Testing import Testing
@Suite("App Tests") @Suite("App Tests")
struct AppTests { struct AppTests {
private func withApp(_ test: (Application) async throws -> ()) async throws { private func withApp(_ test: (Application) async throws -> ()) async throws {
let app = try await Application.make(.testing) let app = try await Application.make(.testing)
do { do {
try await configure(app) try await configure(app)
try await test(app) try await test(app)
} }
catch { catch {
try await app.asyncShutdown() try await app.asyncShutdown()
throw error throw error
} }
try await app.asyncShutdown() try await app.asyncShutdown()
} }
@Test("Test Hello World Route") @Test("Test Hello World Route")
func helloWorld() async throws { func helloWorld() async throws {
try await withApp { app in try await withApp { app in
try await app.test(.GET, "hello", afterResponse: { res async in try await app.test(.GET, "hello", afterResponse: { res async in
#expect(res.status == .ok) #expect(res.status == .ok)
#expect(res.body.string == "Hello, world!") #expect(res.body.string == "Hello, world!")
}) })
} }
} }
} }