Skip to content

Instantly share code, notes, and snippets.

View adam-fowler's full-sized avatar

Adam Fowler adam-fowler

View GitHub Profile
@adam-fowler
adam-fowler / webserver.md
Last active December 3, 2021 15:12
Local web server written in swift

For this to work you need swift-sh installed.

#!/usr/bin/env swift-sh

import ArgumentParser   // apple/swift-argument-parser
import HummingbirdFoundation  // hummingbird-project/hummingbird

struct WebServer: ParsableCommand {
    @Option(name: .shortAndLong)
 var port: Int = 8001
@adam-fowler
adam-fowler / Job Encoding Decoding.md
Last active October 26, 2021 10:21
Decoding/Encoding of Polymorphic payloads (taken from Job implementation in https://github.com/hummingbird-project/hummingbird)
/// For a job to be decodable, it has to be registered. Call `MyJob.register()` to register a job.
public protocol HBJob: Codable {
    /// Unique Job name
    static var name: String { get }
}

extension HBJob {
    /// register job
    public static func register() {
@adam-fowler
adam-fowler / SequenceAsyncFunctions.md
Last active November 17, 2021 16:08
Sequence `forEach` and `map` that uses an async closure

Implement Sequence.forEach and Sequence.map that takes an async closure.

@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension Sequence {
    // named `asyncForEach` as naming it `forEach` confuses the compiler
    func asyncForEach(_ body: @escaping (Element) async throws -> Void) async rethrows {
        try await withThrowingTaskGroup(of: Void.self) { group in
            self.forEach { element in
                group.addTask {

Using MQTTNIO to connect to a AWS IoT Broker with WebSockets

import SotoSignerV4

let host = "MY_AWS_IOT_ENDPOINT"
let port = 443
let headers = HTTPHeaders([("host", host)])
let signer = AWSSigner(
 credentials: StaticCredential(accessKeyId: "MYACCESSKEY", secretAccessKey: "MYSECRETKEY"), 
enum RequestProvider<Request> {
    case `static`(Request)
    case dynamic((EventLoop)->EventLoopFuture<Request>)

    func getRequest(on eventLoop: EventLoop) -> EventLoopFuture<Request> {
        switch self {
        case .static(let request):
            return eventLoop.makeSucceededFuture(request)
        case .dynamic(let requestFunction):

Extending Vapor Application and Request to support AWS SDK Swift

import AWSS3
import Vapor

public extension Application {
    var aws: AWS {
        .init(application: self)
    }
@adam-fowler
adam-fowler / gist:de8bc87edafbafaf1d270e5f17197369
Created May 29, 2020 15:24
AWSSDKSwift: Create User report
```swift
let cloudTrail = CloudTrail(region:.euwest1)
let ses = SES(region:.euwest1)
let request = CloudTrail.LookupEventsRequest(
endTime:TimeStamp(Date()),
lookupAttributes: [.init(attributeKey: .username, attributeValue: "adamfowler")],
startTime: TimeStamp(Date(timeIntervalSinceNow: -24*60*60))
)
// generate report
@adam-fowler
adam-fowler / gist:9efe36a8f3641f3a6e020ae1825c86ad
Created February 7, 2020 16:42
NIO Transport services fail
import Network
import NIO
import NIOHTTP1
import NIOTransportServices
/// Channel Handler for serializing request header and data
class HTTPClientRequestSerializer : ChannelOutboundHandler {
typealias OutboundIn = Void
typealias OutboundOut = HTTPClientRequestPart
@adam-fowler
adam-fowler / gist:cb3ff5936dec1467da56ea633494e9a6
Created December 29, 2019 13:04
Comparing CryptoSwift to OpenSSL functions imported by AWSSDKSwiftCore
import AWSSDKSwiftCore
import CryptoSwift
import Foundation
extension Array where Element: FixedWidthInteger {
static func random(count: Int) -> [Element] {
var array = self.init()
for _ in 0..<count {
array.append(.random(in: Element.min..<Element.max))
}
@adam-fowler
adam-fowler / gist:69897480ce8b78bb445a10b218b0c463
Created September 23, 2019 16:53
Logging Middleware for Vapor
import Vapor
/// Middleware for outputting all http requests and their responses
final class LoggingMiddleware : Middleware, ServiceType {
static func makeService(for container: Container) throws -> Self {
return try .init(environment: container.environment, log: container.make())
}
init(environment: Environment, log: Logger) {
self.environment = environment